多线程实现顺序循环打印

[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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值