首页 > 代码库 > Java多线程之notifyAll的作用域
Java多线程之notifyAll的作用域
notifyAll()因某个特定锁而被调用时,只有等待这个锁的任务才会被唤醒。
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); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。