[quote]原题:有三个线程ID分别是A、B、C,请用多线程编程在屏幕上循环打印10次ABCABC…… 。[/quote]
[quote]以上代码对该题做了适当拓展,支持不同的ID取值及打印次数,同时有效控制了并发可能引起的打印错乱。
遗留问题:死锁风险。就代码来看,任一线程异常中断后,可能会造成其它线程持久wait。解决方法有待研究。[/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]