package ThreadTest;
public class ThreeThread {
static class Node{
private int flag = 0;
private int index = 0;
}
static class Thread1 extends Thread{
Node node;
private final int threadId;
private final Object o = new Object();
public Thread1(int threadId, Node node){
this.threadId = threadId;
this.node = node;
}
@Override
public void run() {
while(node.index <= 10) {
synchronized (o) {
if (threadId == node.flag) {
System.out.println("线程ID:" + this.threadId + "打印: " + node.index++);
node.flag = (node.index + 1) % 3;
}
}
}
}
}
public void print(){
}
public static void main(String[] args){
Node node = new Node();
Thread1 t1 = new Thread1(0, node);
Thread1 t2 = new Thread1(1, node);
Thread1 t3 = new Thread1(2, node);
t1.start();
t2.start();
t3.start();
}
}
三个线程轮流打印0到10
最新推荐文章于 2023-05-26 22:48:54 发布