您的位置:首页 > 编程语言 > Qt开发

QTP学习记录(三)

2008-12-04 17:38 183 查看
朋友问的题,试着写写。也许有其他实现方式,感觉题目应该是考察线程间协作wait和notify所以选择如下方式实现:
/**
* @author my_corner
* 2011-12-26
*/
public class ThreadPrint {

/**
* @author my_corner
* @param
* @return
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
PrintTask task = new PrintTask();

Thread a = new Thread(task);
a.setName("a");
Thread b = new Thread(task);
b.setName("b");
Thread c = new Thread(task);
c.setName("c");

a.start();
b.start();
c.start();

}

}

class PrintTask implements Runnable{
private int times = 0;

/**
*
*/
@Override
public void run() {
while(times<30){
synchronized (this) {
if(times%3==0){
if("a".equals(Thread.currentThread().getName())){
System.out.print("a");
times++;
this.notifyAll();
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(times%3==1){
if("b".equals(Thread.currentThread().getName())){
System.out.print("b");
times++;
this.notifyAll();
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(times%3==2){
if("c".equals(Thread.currentThread().getName())){
System.out.print("c");
times++;
this.notifyAll();
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: