-2

我正在尝试编写程序以了解有关 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;
    }
}
4

1 回答 1

0

你的while循环是倒置的。条件应该是myTimeCount.getCount() < 5

于 2013-03-09T23:56:24.383 回答