码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程之notifyAll的作用域

时间:2014-05-29 21:36:13      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

notifyAll()因某个特定锁而被调用时,只有等待这个锁的任务才会被唤醒。

bubuko.com,布布扣
package Thread.Wait;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Blocker {
    synchronized void waitingCall() {
        try {
            while (!Thread.interrupted()) {
                wait();
                System.out.println(Thread.currentThread() + " ");
            }
        } catch (Exception e) {
            // OK to exit this way
        }
    }

    synchronized void prod() {
        notify();
    }

    synchronized void proAll() {
        notifyAll();
    }
}

class Task implements Runnable {
    static Blocker blocker = new Blocker();

    public void run() {
        blocker.waitingCall();
    }
}

class Task2 implements Runnable {
    static Blocker blocker = new Blocker();

    public void run() {
        blocker.waitingCall();
    }
}

public class NotifyVsNotifyAll {
    public static void main(String[] args) throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new Task());
        }
        exec.execute(new Task2());
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            boolean prod = true;

            @Override
            public void run() {
                if (prod) {
                    System.out.println("\nnotify() ");
                    Task.blocker.prod();
                    prod = false;
                } else {
                    System.out.println("\nnotifyAll()");
                    Task.blocker.proAll();
                    prod = true;
                }
            }
        }, 400, 400);
    }
}
bubuko.com,布布扣

 

Java多线程之notifyAll的作用域,布布扣,bubuko.com

Java多线程之notifyAll的作用域

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zhuawang/p/3758168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!