Java通知和等待异常



我正试图编写一个程序来了解更多关于Java线程。该程序的逻辑很简单,当TimeCount类计数变量等于5时,第一个线程将运行。

这是一个传统的等待通知问题。我不知道代码中的错误在哪里?请帮助。

public class TestThread {
    public static void sleep(int time) {
        try {
            Thread.currentThread().sleep(time);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
        final MyTimeCount myTimeCount = new MyTimeCount();
        final ReentrantLock myLock = new ReentrantLock();
        final Condition cvar = myLock.newCondition();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                myLock.lock();
                try {
                    while (myTimeCount.getCount() >= 5) {
                        cvar.await();
                    }
                    System.out.println("--- data is ready, so we can go --- ");
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    myLock.unlock();
                }               
            }
        });
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    int count = myTimeCount.increase();
                    if (count == 5) {
                        cvar.signalAll();
                        break;
                    }
                    sleep(6000);
                }
            }
        });
        //-----------
        t1.start();       
        t3.start();
    }
}
class MyTimeCount {
    int count;
    public int increase() {
        count++;
        System.out.println("time increase count=" + count);
        return count;
    }
    public int decrease() {
        count--;
        System.out.println("time decrease count=" + count);
        return count;
    }
    public int getCount() {
        return count;
    }
}

while循环是反转的。条件应为myTimeCount.getCount() < 5

最新更新