欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三线程联系输出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]
相关标签: 线程