wait和notify的基础用法
用于线程间的通信,话不多说,见代码
package waitnotify;
public class SimpleWN {
private static final SimpleWN obj = new SimpleWN();
public static void main(String[] args) {
T1 t1 = new T1(obj);
T2 t2 = new T2(obj);
new Thread(t1).start();
new Thread(t2).start();
}
}
package waitnotify;
public class T1 implements Runnable {
private SimpleWN obj;
public T1(SimpleWN obj) {
super();
this.obj = obj;
}
@Override
public void run() {
fun1();
fun2();
fun3();
}
public void fun1() {
System.out.println("T1 线程执行方法1");
}
public void fun2() {
System.out.println("T1 线程执行方法2");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
obj.notify();
}
}
public void fun3() {
System.out.println("T1 线程执行方法3");
}
}
package waitnotify;
public class T2 implements Runnable {
private SimpleWN obj;
public T2(SimpleWN obj) {
super();
this.obj = obj;
}
@Override
public void run() {
funA();
funB();
funC();
}
public void funA() {
System.out.println("T2 执行方法A");
}
public void funB() {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("T2 执行方法B");
}
public void funC() {
System.out.println("T2 执行方法C");
}
}