多线程——等待-唤醒机制的优化

package com.qianfeng.demo03;
/**
 * 等待唤醒机制的优化
 * 代码的优化?
 * 把同步的代码的操作内容定义在资源当中,比较好,为什么?
 * 因为更符合面向对象的思想
 * 
 * 把类中的方法设置为由synchronized修饰符修饰,那么他的对象就是线程安全的对象。
 * 
 * 优化步骤:
 * 1.成员私有化
 * 2.提供了set和get的方法。
 * 3.把代码当中直接调用属性的过程改为调用方法了。
 * */
//描述资源的类
class Resource3{
	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;
		
		//存放数据,更改标记
		flag = true;
		this.notify();
		
	}
	
	public synchronized void out(){
		if (!flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println(this.name+".........."+this.sex);
		//取出数据,更改标志位
		flag = false;
		this.notify();
	}
}
//如果标志位是true,就去做输出的操作,如果标志位是false,就去做输入操作。
//描述输入的任务的类。
class Input3 implements Runnable{
	Resource3 r;
	//任务一旦初始化就将资源传进来,任务一产生必须有资源
	public Input3(Resource3 r) {
		this.r = r;
	}

	@Override
	public void run() {
		int x = 0;
		while (true) {
			if (x==0) {
				r.set("小红", "女");
			}else {
				r.set("小明", "男");
			}
			x = (x+1)%2;
		}
	}
	
}
//描述输出任务的类
class Output3 implements Runnable{
	Resource3 r ;
	
	public Output3(Resource3 r) {
		super();
		this.r = r;
	}

	@Override
	public void run() {
		while (true) {
			r.out();
		}
	}
}
public class ResourceDemo03 {

	public static void main(String[] args) {
		//创建资源对象
		Resource3 r = new Resource3();
		//创建线程任务对象
		Input3 input = new Input3(r);
		Output3 output = new Output3(r);
		//创建线程对象
		Thread t1 = new Thread(input);    //输入,存
		Thread t2 = new Thread(output);   //输出,取
		
		//开启线程
		t1.start();
		t2.start();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值