1 3 package jodd.util; 4 5 import junit.framework.TestCase; 6 7 import java.util.Random ; 8 9 public class MutexTest extends TestCase { 10 11 static Mutex lock = new Mutex(); 12 13 static int count = 0; 14 static int end = 0; 15 16 static Random r = new Random (); 17 18 static class FooThread extends Thread { 19 int id; 20 FooThread(int id) { 21 this.id = id; 22 } 23 public void run() { 24 if (r.nextBoolean() == true) { 25 lock.lock(); 26 } else { 27 while (lock.tryLock() == false) { 28 ThreadUtil.sleep(30); 29 } 30 } 31 assertEquals(0, count); 32 count++; 33 assertEquals(1, count); 34 ThreadUtil.sleep(40); 35 assertEquals(1, count); 36 count--; 37 assertEquals(0, count); 38 lock.unlock(); 39 end++; 40 } 41 } 42 43 public void testMutex() { 44 for (int i = 0; i < 10; i++) { 45 end = 0; 46 int total = 100; 47 while (total > 0) { 48 FooThread thread = new FooThread(total); 49 thread.setDaemon(false); 50 thread.start(); 51 total--; 52 } 53 while (end < 100) { 54 ThreadUtil.sleep(25); 55 } 56 assertEquals(100, end); 57 } 58 59 } 60 } 61 | Popular Tags |