这篇博客主要是通过模拟生活中的生产者消费者的案例,来进一步熟悉线程的相关操作。
/**
* 生产者---厨师
*/
class Productor implements Runnable {
private Food food;
public Productor(Food food) {
this.food = food;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
food.set("韭菜炒鸡蛋","男人的好食品,多吃有益健康");
} else {
food.set("葱爆腰花","补肾气,通膀胱,我好她也好");
}
}
}
}
/**
* 消费者---服务员
*/
class Consumer implements Runnable
{
private Food food;
public Consumer(Food food)
{
this.food=food;
}
@Override
public void run() {
for (int i=0;i<100;i++){
food.get();
}
}
}
/**
* 产品---食物
*/
class Food{
private String name;
private String content;
//标记变量
private boolean flag=true;
//true表示可以生产,false表示可以消费
public synchronized void set(String name,String concent)
{
if(!flag)
{
try {
this.wait();//让当前线程进入等待池等待,没有指定时间,
// 需要其它线程唤醒,释放对象锁,让出CPU
//sleep释放CPU,不释放对象锁住
} catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
this.setName(name);
try {
Thread.sleep(300);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
this.setContent(concent);
flag=false;//表示可以消费
this.notify();//唤醒在该监视器上的一个线程
}
//消费产品
public synchronized void get()
{
if(flag)
{
try {
this.wait();
}catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
try {
Thread.sleep(300);
}catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println(this.getName()+":"+this.getContent());
flag=true;
this.notify();
}
public Food() {
}
public Food(String name, String content) {
this.name = name;
this.content = content;
}
public String getName() {
return name;
}
public String getContent() {
return content;
}
public void setName(String name) {
this.name = name;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
", content='" + content + '\'' +
'}';
}
}
public class ThreadDemo {
public static void main(String args[])
{
Food food=new Food();
Productor productor=new Productor(food);
Consumer consumer=new Consumer(food);
new Thread(productor).start();
new Thread(consumer).start();
}
}