多執行緒實現順序迴圈列印

jupiterpan發表於2020-04-05
[quote]原題:有三個執行緒ID分別是A、B、C,請用多執行緒程式設計在螢幕上迴圈列印10次ABCABC…… 。[/quote]

package jstyle;

public class TestTread {
private int i,j,count,times;
private Object o = new Object();
public void IdPrint(int t,String...ids){
while(Thread.activeCount()!=1){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(Thread.activeCount()==1){
System.out.println();
}
}
times = t;
count = ids.length;
for(i=0,j=0; j<count; j++){
new Thread(new Runnable(){
int pos = j;
public void run(){
synchronized (o) {
while(i<times*count){
if(i%count==pos){
i++;
System.out.print(Thread.currentThread().getName());
o.notifyAll();
}
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notifyAll();
}
};
},ids[j]).start();
}
}
public static void main(String[] args) throws InterruptedException{
new TestTread().IdPrint(9,"a","b","c");
new TestTread().IdPrint(1,"d","e");
}

}

abcabcabcabcabcabcabcabcabc
de

[quote]以上程式碼對該題做了適當擴充,支援不同的ID取值及列印次數,同時有效控制了併發可能引起的列印錯亂。

遺留問題:死鎖風險。就程式碼來看,任一執行緒異常中斷後,可能會造成其它執行緒持久wait。解決方法有待研究。[/quote]

相關文章