Java-马士兵设计模式学习笔记-观察者模式-OOD线程

一、概述

1.情景:孩子睡觉,醒后要吃东西,用java模拟此情况

2.设计:child类,Dad类,都继承Runnable,dad线程监视child线程(缺点:因为要监视,所以耗cup资源)

二、代码

Test.java

class Child implements Runnable {

	

	private boolean wakenUp = false;

	

	public boolean isWakenUp() {

		return wakenUp;

	}



	public void setWakenUp(boolean wakenUp) {

		this.wakenUp = wakenUp;

	}



	public void wakeUp(){

		wakenUp = true;

	}



	@Override

	public void run() {

		try {

			Thread.sleep(3000);

		} catch (Exception e) {

			e.printStackTrace();

		}

		wakeUp();

	}

}



class Dad implements Runnable{



	Child c;

	

	public Dad(Child c) {

		this.c = c;

	}



	@Override

	public void run() {

		while(!c.isWakenUp()){

			try {

				Thread.sleep(1000);

			} catch (Exception e) {

				e.printStackTrace();

			}

		}

		

		feed(c);

	}



	private void feed(Child c) {

		System.out.println("feed child");

	}

	

}



public class Test {



	public static void main(String[] args) {

		Child c = new Child();

		Dad d = new Dad(c);

		new Thread(c).start();

		new Thread(d).start();;

	}

}

  

运行结果:

3秒后出现

你可能感兴趣的:(观察者模式)