zoukankan      html  css  js  c++  java
  • Java多线程

    package me.ereach;
    
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    
    public class ThreadDemo {
        public static void main(String[] args) {
            ExecutorService es = Executors.newFixedThreadPool(255);
    
            Egg egg01 = new Egg();
    
            for (int i = 0; i < 10; i++) {
                es.execute(new Runnable() {
                    @Override
                    public void run() {
                        egg01.getEgg();
                    }
                });
    
                es.execute(new Runnable() {
                    @Override
                    public void run() {
                        egg01.putEgg();
                    }
                });
    
            }
    
            es.shutdown();
        }
    }
    
    class Egg {
        private int count;
    
        public Egg() {
            this.count = 0;
        }
    
        public synchronized void putEgg() {
            while (this.count > 0) {
                try {
                    wait();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            this.count = 1;
            System.out.println(this.count + " egg put.");
            notify();
        }
    
        public synchronized int getEgg() {
            while (this.count == 0) {
                try {
                    wait();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            int egg = this.count;
            this.count = 0;
            System.out.println(egg + " egg get.");
            this.count = 0;
            notify();
    
            return egg;
        }
    
    }
    

      

       

  • 相关阅读:
    POJ 3093 Margaritas on the River Walk(背包)
    BZOJ 2287 【POJ Challenge】消失之物(DP+容斥)
    WC2017 Day1
    WC2017 Day0
    WC2017 Conclusion
    WC2017 Day6
    UOJ #58 糖果公园
    WC2017 Day5
    codevs 1946 阿狸的打字机
    HDU 2457 DNA_repair
  • 原文地址:https://www.cnblogs.com/jinzd/p/7553142.html
Copyright © 2011-2022 走看看