多线程的开发中有一个最经典的操作案例,就是生产者-消费者,生产者不断生产产品,消费者不断取走产品。
sleep与wait区别:
sleep: 让线程进行进入休眠状态,让出cpu的时间片,不释放监视器所有权(对象锁)
wait: 让线程进入等待状态,让出cpu的时间片,并释放监视器所有权,等待其他线程通过notify方法唤醒
生产者与消费者案例代码示例:
package com.booy;
public class ProducterCustomerDemo {
public static void main(String[] args) {
Food f = new Food();
Producter producter = new Producter(f);
Customer customer = new Customer(f);
Thread t1= new Thread(producter);
Thread t2= new Thread(customer);
t1.start();
t2.start();
}
}
//生产者
class Producter implements Runnable{
private Food food;
public Producter(Food food){
this.food=food;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
if(i%2==0){
food.set("包子豆腐","肉香四溢");
}else {
food.set("炸鸡腿","香脆鲜美,外酥里嫩");
}
}
}
}
//消费者
class Customer implements Runnable{
private Food food;
public Customer(Food food){
this.food=food;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
food.get();
}
}
}
//食物类
class Food{
private String name;
private String desc;
private boolean flag = true;//true表示可以生产,flase表示可以消费
//生产食物
public synchronized void set(String name, String desc){
if(!flag){
try {
this.wait();//进入休眠状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.desc = desc;
flag = false;
this.notify();//唤醒线程等待中的随机一个
}
//消费食物
public synchronized void get(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"-->"+desc);
flag = true;
this.notify();
}
public Food() {}
}
/**
运行结果:
包子豆腐-->肉香四溢
炸鸡腿-->香脆鲜美,外酥里嫩
包子豆腐-->肉香四溢
炸鸡腿-->香脆鲜美,外酥里嫩
包子豆腐-->肉香四溢
炸鸡腿-->香脆鲜美,外酥里嫩
包子豆腐-->肉香四溢
炸鸡腿-->香脆鲜美,外酥里嫩
包子豆腐-->肉香四溢
炸鸡腿-->香脆鲜美,外酥里嫩
*/