zoukankan      html  css  js  c++  java
  • 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("
    notify() ");
                        Task.blocker.prod();
                        prod = false;
                    } else {
                        System.out.println("
    notifyAll()");
                        Task.blocker.proAll();
                        prod = true;
                    }
                }
            }, 400, 400);
        }
    }
  • 相关阅读:
    宝宝的成长脚印9/2
    宝宝的成长脚印9/5
    手动作花灯10/6
    EasyUI中EasyLoader加载数组模块
    easyui常用属性
    VS2010如何在一个web项目中使用APP_CODE下的自定义类
    MSSQL系统常用视图命令及其作用
    db_autopwn渗透流程
    渗透测试工具Nmap从初级到高级
    EasyUI中在表单提交之前进行验证
  • 原文地址:https://www.cnblogs.com/zhuawang/p/3758168.html
Copyright © 2011-2022 走看看