生产者消费者之等待唤醒机制思路图解及代码实现

在这里插入图片描述
等待唤醒:

Object类中提供了三个方法:
	wait():等待
	notify():唤醒单个线程
	notifyAll():唤醒所有线程
为什么这些方法不定义在Thread类中呢?
	这些方法的调用必须通过锁对象调用,而我们刚才使用的锁对象是任意锁对象。
	所以,这些方法必须定义在Object类中。因为他才代表任意对象
public class Student {
	String name;
	int age;
	boolean flag;//默认情况是没有数据
}
public class SetThread implements Runnable{
	private Student s=new Student();
	private int x=0;
	public SetThread(Student s){
		this.s=s;
	}
	@Override
	public void run() {
		while(true){
			synchronized (s) {
				//判断有没有
				if(s.flag){
					try {
						s.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(x%2==0){
					s.name="张三";
					s.age=24;
				}else{
					s.name="李四";
					s.age=34;
				}
				x++;
				
				//修改标记
				s.flag=true;
				//唤醒线程
				s.notify();
			}
		}
	}
	
}

public class GetThread implements Runnable {
	private Student s = new Student();

	public GetThread(Student s) {
		this.s = s;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			synchronized (s) {
				if(!s.flag){
					try {
						s.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println(s.name + "---" + s.age);
				//修改标记
				s.flag=false;
				//唤醒等待
				s.notify();
			}
		}
	}

}

/*
 * 分析:
 * 资源类:Student
 * 设置学生数据:SetThread(生产者)
 * 获取学生数据:GetThread(消费者)
 * 测试类:StudentDemo
 */
public class StudentDemo {
	public static void main(String[] args) {
		//创建资源
		Student s=new Student();
		
		//设置和获取的类
		SetThread st=new SetThread(s);
		GetThread gt=new GetThread(s);
		
		//线程类
		Thread t1=new Thread(st);
		Thread t2=new Thread(gt);
		
		t1.start();
		t2.start();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java后端指南

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值