JavaSE编程案例系列(9~100)——等待唤醒机制(单例模型)

实现下列案例

多个线程在处理同一个资源,但是处理的动作(线程的任务)却不相同。通过一定的手段使各个线程能有效的利用资源。而这种手段即—— 等待唤醒机制

在这里插入图片描述

如上图说示,输入线程向Resource中输入name ,sex , 输出线程从资源中输出,先要完成的任务是:

  1. 当input发现Resource中没有数据时,开始输入,输入完成后,叫output来输出。如果发现有数据,就wait();
  2. 当output发现Resource中没有数据时,就wait() ;当发现有数据时,就输出,然后,叫醒input来输入数据。

建立模拟资源类

public class Resource {
		private String name;
		private String sex;
		//唤醒标志位
		private boolean flag;
		//输入变量名的方法
		public synchronized void set(String name,String sex){
			if(flag)
				try{wait();}catch(InterruptedException e){e.printStackTrace();}
			//设置成员变量
			this.name = name;
			this.sex = sex;
			//设置变量后,Resoure中有值,标记为true
			flag = true;
			//唤醒output
			this.notify();
		}
		//输出变量名的方法
		public synchronized void out(){
			if(!flag)
				try{wait();}catch(InterruptedException e){e.printStackTrace();}
			//输出线程将数据输出
			System.out.println("姓名:"+name+",性别:"+sex);
			flag = false;
			//唤醒input,进行数据输入
			this.notify();		
		}
}

创建输入线程任务类

public class Input implements Runnable {
		private Resource r;
		
		public Input(Resource r) {
				this.r = r;
		}

		public void run(){
			int count  = 0;
			while(true){
				if(count == 0){
					r.set("小明", "男");
				}else{
					r.set("小红", "女");
				}
				//在两个数据中进行切换
				count = (count + 1) % 2;
			}
		}
}

创建输出线程任务类

public class Output implements Runnable {
		private Resource r ;
		
		public Output(Resource r){
			this.r = r;
		}
		
		@Override
		public void run(){
			while(true){
				r.out();
			}
		}
}

创建测试类

public class ResourceDemo {
		public static void main(String[] args) {
			//资源对象
			Resource r = new Resource();
			//任务对象
			Input in = new Input(r);
			Output out = new Output(r);
			//线程对象
			Thread t1 = new Thread(in);
			Thread t2 = new Thread(out);
			//开启线程
			t1.start();
			t2.start();
		}
}

猜你喜欢

转载自blog.csdn.net/jiangyi_1612101_03/article/details/84704977