FileDocCategorySizeDatePackage
TestSemaphore.javaAPI DocphoneME MR2 API (J2ME)4014Wed May 02 18:00:00 BST 2007com.sun.midp.test

TestSemaphore

public class TestSemaphore extends TestCase

Fields Summary
com.sun.cldc.util.Semaphore
sema
Constructors Summary
Methods Summary
public voidrunTests()

        declare("testOne");
        testOne();
        declare("testTwo");
        testTwo();
        declare("testBlock");
        testBlock();
        declare("testManyBlock");
        testManyBlock();
    
voidsleep(int s)

        try {
            Thread.sleep(s);
        } catch (InterruptedException ignore) { }
    
voidtestBlock()

        sema = new Semaphore(0);

        Blocker t1 = new Blocker(sema);

        assertTrue(! t1.isBlocked);
        t1.start();
        sleep(100);
        assertTrue(t1.isBlocked);
        sema.release();
        try {
            t1.join();
        } catch (InterruptedException ignore) { }
        assertTrue(! t1.isBlocked);

        sema = null;
    
voidtestManyBlock()

        sema = new Semaphore(0);
        final int NTHREADS = 10;

        Blocker ta[] = new Blocker[NTHREADS];
        for (int i = 0; i < NTHREADS; i++) {
            ta[i] = new Blocker(sema);
        }

        for (int i = 0; i < NTHREADS; i++) {
            assertTrue("blocked initially", !ta[i].isBlocked);
        }

        for (int i = 0; i < NTHREADS; i++) {
            ta[i].start();
        }
        
        sleep(100);

        for (int i = 0; i < NTHREADS; i++) {
            assertTrue("not blocked after start", ta[i].isBlocked);
        }

        sema.release();
        sema.release();
        sema.release();

        sleep(100);

        int count = 0;
        for (int i = 0; i < NTHREADS; i++) {
            if (ta[i].isBlocked)
                ++count;
        }

        assertEquals("blocked " + count + "instead of 7", 7, count);

        sema.release();
        sema.release();
        sema.release();
        sema.release();
        sema.release();
        sema.release();
        sema.release();

        sleep(100);

        count = 0;
        for (int i = 0; i < NTHREADS; i++) {
            if (ta[i].isBlocked)
                ++count;
        }

        assertEquals("all not unblocked", 0, count);

        for (int i = 0; i < NTHREADS; i++) {
            try {
                ta[i].join();
            } catch (InterruptedException ignore) { }
        }
    
voidtestOne()

        Semaphore sema = new Semaphore(1);
        sema.acquire();
        assertTrue(true);
    
voidtestTwo()

        Semaphore sema = new Semaphore(0);
        sema.release();
        sema.acquire();
        assertTrue(true);