5個執行緒依次列印1A2B3C4D5E1F2G...
阿新 • • 發佈:2019-02-04
問題要求:
1.使用5個執行緒
2.五個執行緒依次列印1A2B…,即第一個執行緒負責列印1(A、F)等等。
解決思路:
1.輪詢count ,當count滿足當前執行緒的列印條件後,列印
2.採用wait和notifyAll進行通訊
相關方法:
1.wait()方法的作用是將當前執行的執行緒掛起(即讓其進入阻塞狀態),直到notify或notifyAll方法來喚醒執行緒.
2.notify和notifyAll的區別在於前者只能喚醒monitor上的一個執行緒,對其他執行緒沒有影響,而notifyAll則喚醒所有的執行緒
實驗程式碼:
public class PrintLettersInorder {
static Object object = new Object();
static int count = 0 ;
static class MyPrintThread extends Thread{
int index ;
public MyPrintThread(int index){
this.index = index;
}
@Override
public void run() {
synchronized (object){
while (count < 26){
try{
//滿足列印條件後,列印並將count+1,然後喚醒其他執行緒,不滿足條件則掛起
if (count%5 == (index-1)){
char c = (char) ('A' + count) ;
System.out.println(index+""+c);
count ++ ;
object.notifyAll();//喚醒其他執行緒
}
//不滿足條件,掛起
object.wait();
}catch (InterruptedException ex){
ex.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread thread1 = new MyPrintThread(1);
Thread thread2 = new MyPrintThread(2);
Thread thread3 = new MyPrintThread(3);
Thread thread4 = new MyPrintThread(4);
Thread thread5 = new MyPrintThread(5);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
while (count < 26);
System.exit(0);
}
}
實驗結果:
1A
2B
3C
4D
5E
1F
2G
3H
4I
5J
1K
2L
3M
4N
5O
1P
2Q
3R
4S
5T
1U
2V
3W
4X
5Y
1Z
存在一個問題,執行緒沒有結束,於是在主執行緒裡面加了 如下程式碼:
while (count < 26);
System.exit(0);
使得26個字母列印完後程序結束