一、基本使用
public class NotifyAndWait {
public static void main(String[] args) throws InterruptedException {
Person p=new Person();
MyThread myThread=new MyThread(p);
MyThread1 m1=new MyThread1(p);
myThread.setName("1");
m1.setName("2");
myThread.start();
Thread.sleep(1000);
m1.start();
}
}
class MyThread extends Thread{
Person person ;
public MyThread(Person person){
this.person=person;
}
@Override
public void run() {
synchronized (person){
System.out.println(Thread.currentThread().getName()+"即将wait");
try {
person.wait();
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+"执行完毕");
}
}
}
class MyThread1 extends Thread{
Person person ;
public MyThread1(Person person){
this.person=person;
}
@Override
public void run() {
synchronized (person){
System.out.println(Thread.currentThread().getName()+"开始运行");
try {
person.notify();
System.out.println("即将唤醒等待者");
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()+"执行完毕");
}
}
}
执行结果:
1即将wait
2开始运行
即将唤醒等待者
2执行完毕
1执行完毕
wait和notify方法都必须在 锁中执行,否则会报错。
notify所在的同步块执行完了才会释放锁持有的锁,然后其它等待中的程序竞争锁。