实现思路:
主要利用了synchronized对象锁,wait()以及notifyAll()方法。
实验代码:
public class TestThread {
public static void main(String[] args) {
Thread thread1=new Thread(new MyThread(0));
Thread thread2=new Thread(new MyThread(1));
Thread thread3=new Thread(new MyThread(2));
thread1.start();
thread2.start();;
thread3.start();
}
static class MyThread implements Runnable{
private static Object lock=new Object(); //静态对象
private static int count=0; //当前打印到的数字
int no;
public MyThread(int no){
this.no=no;
}
@Override
public void run() {
while(true){
synchronized (lock){
if(count>=100) {
break;
}else if(count%3==no){
count++;
int cur=this.no+1;
System.out.println("第"+cur+"个线程"+"打印了"+count);
}else{
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
};
}
lock.notifyAll(); //唤醒其他等待线程
}
}
}
}
}
结果展示:
结果较长,只展示开头和结尾部分。
…
…