java使用wait和notify實現放水果喫水果(2個線程通信)

使用wait和notify方法僅能實現2個線程之間通信。後面會更新多個線程之間通信。

Farmer:農夫

Child:小孩

Kuang:框(最多放進10個水果)

如果框中的水果等於10就讓農夫休息,如果框中的水果等於0就讓小孩休息。


Farmer:

/**
 * @author :Lee
 * @date :2019/7/16 16:55
 * @description:農夫
 */
public class Farmer implements Runnable {
    @Override
    public void run() {
        while (true) {
            synchronized (Kuang.kuang) {
                if (Kuang.kuang.size() == 10) {
                    try {
                        Kuang.kuang.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                Kuang.kuang.add("apple");
                System.out.println("農夫放進一個蘋果,框中還有:" + Kuang.kuang.size() + "個蘋果");
                Kuang.kuang.notify();
            }
            try {
                TimeUnit.MILLISECONDS.sleep(700);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Child:

/**
 * @author :Lee
 * @date :2019/7/16 16:55
 * @description:小孩
 */
public class Child implements Runnable {


    @Override
    public void run() {
        while (true) {
            synchronized (Kuang.kuang) {
                if (Kuang.kuang.size() == 0) {
                    try {
                        Kuang.kuang.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Kuang.kuang.remove("apple");
                System.out.println("小孩喫掉一個蘋果,框中還剩:" + Kuang.kuang.size() + "個蘋果");
                Kuang.kuang.notify();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

Kuang:

/**
 * @author :Lee
 * @date :2019/7/16 16:54
 * @description:容器 (volatile 可不加)
 */
public class Kuang {
    volatile public static List<Object> kuang = new ArrayList<>();
}

Test:

/**
 * @author :Lee
 * @date :2019/7/16 17:03
 * @description:
 */
public class TestWait {
    public static void main(String[] args) {
        new Thread(new Farmer()).start();
        new Thread(new Child()).start();

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章