-2
我正在嘗試編寫程序以瞭解有關Java線程的更多信息。程序的邏輯很簡單,當TimeCount類的count變量等於5時,第一個線程將運行。Java通知並等待異常?
這是傳統的等待和通知問題。我不知道代碼中的錯誤在哪裏?請幫忙。
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;
}
}
儘量縮小它可能存在的區域,不要粘貼*所有*代碼 – Coffee 2013-03-09 23:54:02
您遇到的問題是什麼以及您希望發生什麼? – 2013-03-09 23:54:05
你需要顯示錯誤? – 2013-03-09 23:56:41