关于wait 和 notifyall的实用方法



import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
* User: guohaozhao
* Date: 13-7-11 10:44
*/
public class multiThreadTest {

private static final byte[] lock = new byte[0];

private static volatile boolean stop = false;

private static class Notifier implements Runnable {

@Override
public void run() {
try {
System.out.println("Notifier is started ...");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}

synchronized (lock) {
lock.notifyAll();
System.out.println("notified all !!");
}

}
}

private static class Waiter implements Runnable {

@Override
public void run() {
synchronized (lock) {
try {
System.out.println(Thread.currentThread().getName() + "waiting ...");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
while (!stop) {
System.out.println(Thread.currentThread().getName() + "doing !!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
}

public static void main(String... args) {

CountDownLatch countDownLatch = new CountDownLatch(1);
Thread thread = new Thread(new Notifier());
thread.start();

for (int i = 0; i < 3; i++) {
Thread _thread = new Thread(new Waiter());
_thread.start();
}

try {
countDownLatch.await(10 * 1000, TimeUnit.MILLISECONDS);
stop = true;
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}

System.out.println("test done !!!");

}
}



执行结果:

Notifier is started ...
Thread-2waiting ...
Thread-3waiting ...
Thread-4waiting ...
notified all !!
Thread-4doing !!!
Thread-3doing !!!
Thread-2doing !!!
Thread-4doing !!!
Thread-2doing !!!
Thread-3doing !!!
Thread-2doing !!!
Thread-3doing !!!
Thread-4doing !!!
test done !!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值