我正在學習線程,所以我想編寫一個程序,它有兩種類型的線程:一種寫隨機數字,另一種檢查當前數字是否與某個特定數字匹配。線程從Numbers類調用write()和read(int)方法。爲了讓事情更清楚,我想我的主要程序是這樣的:Java線程按順序
Numbers n = new Numbers();
new WritingThread(n);
new ReadingThread(n,3);
new ReadingThread(n,5);
所以輸出會是這樣的:
2
7
3 !!! MATCH !!!
8
5 !!! MATCH !!!
1
...
的事情是,線程不按順序執行。我想先執行WritingThread,然後執行所有的ReadingThreads。因爲這樣一個新的隨機數字將被寫入,並且只有一個線程將有機會檢查數字是否匹配。下面是代碼:
類數:
public class Numbers {
int number;
boolean written = false;
public synchronized void write() {
while (written)
try {
wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
number = (int) (Math.random() * 10);
System.out.print("\n" + number);
written = true;
notifyAll();
}
public synchronized void check(int n) {
while (!written)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(" Reading thread: " + Thread.currentThread().getName());
if (n == number)
System.out.print(" !!! MATCH !!! ");
notify();
written = false;
}
}
類WritingThread:
public class WritingThread extends Thread {
Numbers n;
WritingThread(Numbers n){
this.n = n;
start();
}
public void run(){
while(true){
n.write();
}
}
}
類ReadingThread:
public class ReadingThread extends Thread{
Numbers n;
int number;
public ReadingThread(Numbers n, int number){
this.n = n;
this.number = number;
start();
}
public void run(){
while(true){
n.check(number);
}
}
}
和輸出:
3 Reading thread: Thread-2
3 Reading thread: Thread-1 !!! MATCH !!!
0 Reading thread: Thread-2
5 Reading thread: Thread-1
0 Reading thread: Thread-2
0 Reading thread: Thread-1
5 Reading thread: Thread-2 !!! MATCH !!!
8 Reading thread: Thread-1
我知道我能讓它有數字數組來檢查一個線程,但我很好奇它如何可以做到這樣。謝謝。
你在問什麼?嘗試打印匹配,或者閱讀[java.util.concurrent.Future](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html)。 –
我這麼認爲,但如何實現它,在哪裏? – tuks
@ElliottFrisch注意到輸出中的第4行。它應該是匹配的,但它不是,因爲線程1正在檢查匹配,線程2沒有得到機會 – tuks