如何锁定一个线程并等待锁定将在另一个线程中释放

时间:2011-09-24 12:09:04

标签: java concurrency

我只想在主线程中等待,直到运行中的某个事件。 我怎么能用java.util.concurency类来做呢? 谢谢!

P.S。 我的问题是否真的解释得不好,正确性检查是不是很糟糕?我是说这个消息 “哎呀!你的问题无法提交,因为:

您的帖子没有太多上下文来解释代码部分;请更清楚地解释你的情景。“?

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);
    }
}

1 个答案:

答案 0 :(得分:6)

您可以使用CountDownLatch(http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html)。

 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
相关问题