public class Test {
public static void main(String[] args) {
boolean[] flag = {true, false, false};
//打印次数
int count = 10;
Thread t1 = new Thread(new MyRunnable(0, flag, count));
Thread t2 = new Thread(new MyRunnable(1, flag, count));
Thread t3 = new Thread(new MyRunnable(2, flag, count));
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable {
boolean[] flag;
int count;
int i;
public MyRunnable(int i , boolean[] flag, int count) {
this.i = i;
this.flag = flag;
this.count = count;
}
@Override
public void run() {
int j = i + 1 < flag.length ? i + 1 : 0;
while(true){
synchronized(MyRunnable.class){
if(count == 0){
break;
}
while(!flag[i]){
try {
MyRunnable.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(i + 1);
flag[i] = false;
flag[j] = true;
count--;
MyRunnable.class.notifyAll();
}
}
}
}
[Java]三个线程按照顺序循环打印1、2、3
最新推荐文章于 2024-01-20 21:08:27 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)