实例分析Java notifyAll方式的使用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值