三线程联系输出abc
程序员文章站
2022-05-31 14:16:03
...
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 < 300) {
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();
}
}
}
}
}
}
}
引用至:[url]http://www.iteye.com/topic/1119297[/url]
下一篇: 判断线程结束