javaconcurrency

How can I lock in one thread and wait until lock will be released in another thread?


I just want wait in main thread until some event in run. How can I do it using java.util.concurency classes?

public class LockingTest {
    private Lock initLock = new ReentrantLock();

    @Test
    public void waiting(){
        initLock.lock();
        final Condition condition = initLock.newCondition();
        long t1= System.currentTimeMillis();
        Thread th = new Thread(new Runnable(){
            @Override public void run() {

                try {
                    Thread.currentThread().sleep(2000);
                } catch (InterruptedException e) {}
                initLock.unlock();
           }
        });
        th.start();

        try {
            condition.await(3000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {}

        long t2= System.currentTimeMillis();
        System.out.println(t2-t1);
    }
}

Solution

  • You can use CountDownLatch.

    1. init countdownlatch with count value 1
    2. start another thread (Thread A )
    3. call await() in main thread
    4. call countdown() in Thread A