java notifyAll()方法唤醒所有处于阻塞状态的线程继续执行阻塞后的代码逻辑。
/**
* 当方法wait()被执行后,锁被自动释放,但是执行完notify()方式,锁却不自动释放
**/
class ServiceWait {
public void testMethod(Object lock) {
try {
synchronized (lock) {
System.out.println(“begin wait start== ” + System.currentTimeMillis() + ” —ThreadName ” + Thread.currentThread().getName());
lock.wait();
System.out.println(“end wait == ” + System.currentTimeMillis() + ” —ThreadName ” + Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.toString();
}
}
}
class NotifyAllThread extends Thread {
private Object lock;
public NotifyAllThread(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
lock.notifyAll();
}
}
}
class A extends Thread {
private Object lock;
public A(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
ServiceWait serviceWait = new ServiceWait();
serviceWait.testMethod(lock);
}
}
class B extends Thread {
private Object lock;
public B(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
ServiceWait serviceWait = new ServiceWait();
serviceWait.testMethod(lock);
}
}
class C extends Thread {
private Object lock;
public C(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
ServiceWait serviceWait = new ServiceWait();
serviceWait.testMethod(lock);
}
}
public static void main(String[] args) {
Object lock = new Object();
A a = new A(lock);
a.start();
B b = new B(lock);
b.start();
C c = new C(lock);
c.start();
//等待一个时间,可以清晰看到,上面的线程一直处于阻塞状态
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//执行通知线程
NotifyAllThread m = new NotifyAllThread(lock);
m.start();
}
}
代码执行结果:
begin wait start== 1469187894185 —ThreadName Thread-0 —–线程A执行run()方法,然后阻塞等待通知
begin wait start== 1469187894185 —ThreadName Thread-1—–线程B执行run()方法,然后阻塞等待通知
begin wait start== 1469187894185 —ThreadName Thread-2—–线程C执行run()方法,然后阻塞等待通知
等待2钟,然后通过线程NotifyAllThread来通知其他的线程继续执行。
end wait == 1469187896186 —ThreadName Thread-2
end wait == 1469187896187 —ThreadName Thread-1
end wait == 1469187896187 —ThreadName Thread-0