问题的难点是线程等待的条件,因为是交替输出,所以任何时候都只能有一个线程运行,其他两个线程进入等待,但是在唤醒线程的时候我们只能一次唤醒两个线程,所以我们需要两个条件,并且三个线程中只能有一个线程满足运行的条件。
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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14620.html