- 两线程通讯:
wait()方法和notify()方法
package codes;
import java.awt.Frame;
public class Test {
public static void main(String[] args) {
final Print p = new Print();
new Thread() {
public void run() {
for (int i=0;i<100;i++) {
try {
p.print1();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
for (int i=0;i<100;i++) {
try {
p.print2();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class Print {
private int flag= 1;
public void print1() throws Exception {
synchronized(this) {
if (flag!=1) {
this.wait();
}
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
flag=2;
this.notify();
}
}
public void print2() throws Exception {
synchronized(this) {
if (flag!=2) {
this.wait();
}
System.out.println("11");
System.out.println("21");
System.out.println("31");
System.out.println("41");
flag=2;
this.notify();
}
}
}