1. 程式人生 > >JAVA wait()和notifyAll()實現線程間通訊

JAVA wait()和notifyAll()實現線程間通訊

all row cache string runnable private sync ide cached

本例是閱讀Think in Java中相應章節後,自己實際寫了一下自己的實現

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/*
假設一個學生,日出而作日落而息
*/
class Student
{
    private boolean Awake=false;
    public synchronized void wakeUp()
    {
        Awake=true;
        System.out.println(
"WakeUp!"); notifyAll(); //notifyAll()寫在這裏!1.臨界區 2.已經做了一些改變 } public synchronized void sleep() { Awake=false; System.out.println("Sleep!"); notifyAll(); //同上 } public synchronized void waitForSleep() throws InterruptedException { while(Awake!=false
) wait(); //等待寫在這裏!1.臨界區 2.等待外界改變的條件 } public synchronized void waitForAwake() throws InterruptedException{ while(Awake!=true) wait(); //同上 } public boolean isAwake() { return Awake; } } class SunRise implements Runnable {//日出 Student student=null; public SunRise(Student student) {
this.student=student; } @Override public void run() { try { while (!Thread.interrupted()) { student.waitForSleep(); //先等待環境變化 TimeUnit.MILLISECONDS.sleep(100); student.wakeUp(); //環境已變化,起床! System.out.println("End Awake"); } }catch (InterruptedException e) { e.printStackTrace(); } } } class SunFall implements Runnable { Student student=null; public SunFall(Student student) { this.student=student; } @Override public void run() { try{ while (!Thread.interrupted()) { student.waitForAwake(); //先等待環境變化 TimeUnit.MILLISECONDS.sleep(100); student.sleep(); //環境已變化,睡覺! System.out.println("End Sleep"); } }catch (InterruptedException e) { e.printStackTrace(); } } } public class Main{ public static void main(String[]args) { Student me=new Student(); SunRise sunRise=new SunRise(me); SunFall sunFall=new SunFall(me); ExecutorService service= Executors.newCachedThreadPool(); service.execute(sunRise); service.execute(sunFall); } }

輸出是

WakeUp!
End Awake
Sleep!
End Sleep

的不停循環。

應該算成功了吧。

JAVA wait()和notifyAll()實現線程間通訊