wait()、notify()方法介绍
1、wait()方法:让当前线程(持有锁的线程)处于等待(阻塞)的状态,并且释放它持有的锁。该线程将处于阻塞状态,直到其它线程调用notify()或者notifyAll()方法唤醒,线程进入就绪状态。
2、wait(long):让当前线程(持有锁的线程)处于等待(阻塞)的状态,直到其它线程调用notify()或者notifyAll()方法或者超过指定的时间,线程进入就绪状态。
3、notify():唤醒持有锁上的其中一个线程。让那个线程从等待状态变成就绪状态。
4、notifyAll():唤醒持有锁上的所有线程。让线程从等待状态变成就绪状态。
示例
public class ThreadDemo extends Thread{
Object object = null;
private String name ;
public ThreadDemo(Object object,String name){
this.object = object;
this.name = name;
}
public void run() {
while(true){
synchronized(object){
try {
Thread.sleep(1000);
object.notify();//唤醒锁上的一个线程,被唤醒的线程处于就绪状态,等待被处理器调用
System.out.println(name +"-----run");
object.wait();//阻塞,释放锁
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Object o = new Object();
ThreadDemo thread1 = new ThreadDemo(o, "thread1");
ThreadDemo thread2 = new ThreadDemo(o, "thread2");
thread1.start();
thread2.start();
}
执行结果:
thread1-----run
thread2-----run
thread1-----run
thread2-----run
thread1-----run
thread2-----run
thread1-----run
thread2-----run
thread1-----run