java等待唤醒机制实现生产者与消费者例子

该例子:

1.如果没有学生,set线程就设置学生的名字和年纪;

2.如果有学生,get线程就取出学生的名字和年龄;


一,SetThread类

package producerandcomsumer;

/**
 * 类描述:设置生产者线程
 * 
 * @author: 张宇
 * @date: 日期: 2018年9月2日 时间: 下午9:40:44
 * @version 1.0
 */
public class SetThread implements Runnable {

	private Student student;
	private int x = 0;

	public SetThread(Student student) {
		this.student = student;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			if (x % 2 == 0) {
				student.set("林青霞", 5);
			} else {
				student.set("张宇", 25);
			}
			x++;
		}
	}
}

二.GetThread类

package producerandcomsumer;

/**
*类描述:获取生产者线程
*@author: 张宇
*@date: 日期: 2018年9月2日 时间: 下午9:41:08
*@version 1.0
 */
public class GetThread implements Runnable {

	private Student student;

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

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			student.get();
		}
	}
}

三,学生类

package producerandcomsumer;

/**
 * 类描述:被消费的对象
 * 
 * @author: 张宇
 * @date: 日期: 2018年9月2日 时间: 下午9:40:27
 * @version 1.0
 */
public class Student {
	private String name;
	private int age;
	private boolean flag;

	public synchronized void set(String name, int age) {
		// 如果有数据就等待
		if (this.flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 设置数据
		this.name = name;
		this.age = age;
		// 修改标记
		this.flag = true;
		this.notify();
	}

	public synchronized void get() {
		// 如果没有数据就等待
		if (!this.flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.out.println(name + ":" + age);
		// 修改标记
		this.flag = false;
		this.notify();
	}
}

四.测试类

package producerandcomsumer;

/**
 * 类描述:设置生产者和消费者
 * 
 * @author: 张宇
 * @date: 日期: 2018年9月2日 时间: 下午9:40:01
 * @version 1.0
 */
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();
	}
}

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/82354833