//3个线程通信
//wait方法调用者必须是锁对象,因此wait方法必须在同步代码中使用
//多个线程通信,wait方法应该放在while循环体中,因为if语句条件判断只执行一次
//多个线程通信,唤醒进程应该要使用notifyAll方法,否则可能会造成阻塞
public class Test2 {
public static void main(String[] args) {
final Print print=new Print();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
print.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
print.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
print.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
class Print {
public static int flag=0;
public void print1() throws InterruptedException{
synchronized (this) {
while (flag!=0) {
this.wait(1000);
}
System.out.print("1");
System.out.print("2");
System.out.print("3");
System.out.print("4");
System.out.print("5");
System.out.println();
flag=1;
//Thread.currentThread().sleep(1000);
this.notifyAll();
}
}
public void print2() throws InterruptedException{
synchronized (this) {
while (flag!=1) {
this.wait(1000);
}
System.out.print("6");
System.out.print("7");
System.out.print("8");
System.out.print("9");
System.out.print("0");
System.out.println();
flag=2;
// Thread.currentThread().sleep(1000);
this.notifyAll();
}
}
public void print3() throws InterruptedException{
synchronized (this) {
while (flag!=2) {
this.wait(1000);
}
System.out.print("a");
System.out.print("b");
System.out.print("c");
System.out.print("d");
System.out.print("e");
System.out.println();
flag=0;
// Thread.currentThread().sleep(1000);
this.notifyAll();
}
}
}
|
|