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;
    }

}

  

   

posted @ 2017-09-19 17:58  Jinzd  阅读(115)  评论(0编辑  收藏  举报