问题的难点是线程等待的条件,因为是交替输出,所以任何时候都只能有一个线程运行,其他两个线程进入等待,但是在唤醒线程的时候我们只能一次唤醒两个线程,所以我们需要两个条件,并且三个线程中只能有一个线程满足运行的条件。
MyObject
package demo06;
public class MyObject {
public int flag=1;
public int i=0;
}
MyThread01
package demo06;
public class MyThread01 extends Thread {
private MyObject obj;
public MyThread01(MyObject obj) {
this.obj = obj;
}
@Override
public void run() {
while (true){
synchronized (obj){
if (obj.i<=98){
try {
if (obj.flag == 2 || obj.flag == 3)obj.wait();
if (obj.flag == 2 || obj.flag == 3) obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+(obj.i++));
obj.flag=2;
obj.notifyAll();//唤醒其他线程
}
}
}
}
}
MyThread02
package demo06;
public class MyThread02 extends Thread {
private MyObject obj;
public MyThread02(MyObject obj) {
this.obj = obj;
}
@Override
public void run() {
while (true){
synchronized (obj){
if (obj.i<=99){
try {
if (obj.flag == 1 || obj.flag == 3)obj.wait();
if (obj.flag == 1 || obj.flag == 3)obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+(obj.i++));
obj.flag=3;
obj.notifyAll();//唤醒其他线程
}
}
}
}
}
MyThread03
package demo06;
public class MyThread03 extends Thread {
private MyObject obj;
public MyThread03(MyObject obj) {
this.obj = obj;
}
@Override
public void run() {
while (true){
synchronized (obj){
if (obj.i<=100){
try {
if (obj.flag == 1 || obj.flag == 2)obj.wait();
if (obj.flag == 1 || obj.flag == 2)obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+(obj.i++));
obj.flag=1;
obj.notifyAll();//唤醒其他线程
}
}
}
}
}
测试类
package demo06;
public class Test01 {
public static void main(String[] args) {
MyObject obj = new MyObject();
new MyThread01(obj).start();
new MyThread02(obj).start();
new MyThread03(obj).start();
}
}