5.27生产者消费者模式在多线程中

package org.westos.生产者消费者模式;


/*
 * 消费者与生产者模式:
 * 消费者:输出数据
 * 生产者:产生数据
 * 这种模式中出了生产者消费者线程,我们还需要设置资源类,即包含数据的对象,还有测试类
 * */
/**
 * 这是一个测试类,它将会输出成片的资源类对象的信息,而不是像SetStudent代码那样相互交叉输出,这是因为没有等待唤醒机制
 * 在加入Java等待唤醒机制后:
 * 消费者:输出数据,当内存中有对象时,才会输出数据,否则处于等待中,向生产者发送信号,要求产生数据
 * 生产者:产生数据,当内存中没有对象时,才会产生对象并设置数据,否则处于等待中,向消费者发送信号,要求输出数据
 * 这就需要我们在Get/SetStudent线程中对资源类对象进行判断
 * */
/**
 * wait()与sleep()的区别
 * 		wait()线程等待,停下当前线程去执行其他线程,会释放锁对象
 * 		sleep()线程睡眠,理解为在线程中加入的一个延时函数,不会释放所对象
 * */
public class Text {

	public static void main(String[] args) {
		Student s = new Student();
		SetStudent ss = new SetStudent(s);
		GetStudent gs = new GetStudent(s);
		Thread t1 = new Thread(ss,"生产者线程");
		Thread t2 = new Thread(gs,"消费者线程");
		t1.start();
		t2.start();
	}
}
package org.westos.生产者消费者模式;
/**
 * 这是一个资源类;
 * 用于包含了学生的姓名,年龄数据
 * */
public class Student {
	private String name;
	private int age;
	//用于等待唤醒机制的判断
	public boolean flag;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student() {
		super();
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
}
package org.westos.生产者消费者模式;
/**
 * 这是一个生产者,用于用于设置资源类对象的数据
 * */
public class SetStudent implements Runnable {
	//将生产者与资源类关联起来
	private Student s;
	public  SetStudent(Student s) {
		this.s =s;
	}
	private int i = 0;//一个用于判断的变量
	@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(i%2==0) {
					s.setName("张三");
					s.setAge(12);
				}else {
					s.setName("李四");
					s.setAge(13);
				}
				i++;
				s.flag = true;
				s.notify();
			}
		}
	}

}
package org.westos.生产者消费者模式;
/**
 * 这是一个消费者
 * */
public class GetStudent implements Runnable{
	private Student s;
	
	public GetStudent(Student s) {
		this.s = s;
	}


	@Override
	public void run() {
		while(true) {
			synchronized (s) {
				if(!s.flag) {
					try {
						s.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println(s);
				s.flag = false;
				s.notify();
			}
		}
	}


}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值