纯html网站模板,视频网站建设费用明细,mysol做的选课网站,html个人网站设计模板桌子上有面条-》吃货执行 桌子上没面条-》生产者制造执行
1、消费者等待
消费者先抢到CPU执行权#xff0c;发现桌子上没有面条#xff0c;于是变成等待wait状态#xff0c;并释放CPU执行权#xff0c;此时的CPU肯定会被厨师抢到#xff0c;初始开始做面条#xff0c;… 桌子上有面条-》吃货执行 桌子上没面条-》生产者制造执行
1、消费者等待
消费者先抢到CPU执行权发现桌子上没有面条于是变成等待wait状态并释放CPU执行权此时的CPU肯定会被厨师抢到初始开始做面条当厨师做完后会对吃货进行提示notify唤醒吃货来吃。
2、生产者等待
厨师先抢到CUP执行权但是桌子上有面条就不能再制作面条只能等待消费者吃完面条才能做消费者吃完后需要唤醒厨师继续做 代码逻辑 厨师
public class Cook extends Thread{Overridepublic void run() {//1循环//2同步代码块//3共享数据是否到末尾Yes//4共享数据是否到末尾Nowhile (true){synchronized (Desk.lock){if (Desk.count0){break;//10碗吃完}else {//厨师的核心逻辑//01判断桌子上是否有食物if (Desk.foodflag1){//02有食物就等待try {Desk.lock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}else {//03没有System.out.println(Thread.currentThread().getName()制作食物);//04改变桌子状态Desk.foodflag1;//05唤醒消费者吃Desk.lock.notifyAll();}}}}}
}
吃货
public class Customer extends Thread{Overridepublic void run() {while (true){synchronized (Desk.lock){if (Desk.count0){break;//10碗吃完}else {//吃货的核心逻辑/** 1.判断桌子上有无面条* 2.没有自己等待* 3.有吃完并唤醒厨师做面条count--* 4.修改桌子状态*/if (Desk.foodflag0){//1.判断桌子上有无面条try {Desk.lock.wait();//2.没有自己等待} catch (InterruptedException e) {throw new RuntimeException(e);}}else {//3.有吃完并唤醒厨师做面条count--Desk.count--;System.out.println(Thread.currentThread().getName()还能再吃Desk.count碗);Desk.lock.notifyAll();//4.修改桌子状态Desk.foodflag0;}}}}}
}
桌子
public class Desk {//通过变量来控制 0:没食物 1有食物public static int foodflag0;//总个数最多做十碗public static int count10;//锁对象public static Object locknew Object();
}//测试类
public class Test {public static void main(String[] args) {Customer customer new Customer();Cook cook new Cook();customer.setName(吃货);cook.setName(厨师);customer.start();cook.start();}
}
3、阻塞队列实现 接口无法new对象只能通过两个实现类第一个可以自定义队列长度。 注意生产者与消费者必须针对同一个阻塞队列阻塞队列可以创建在测试类中 厨师
public class Cook extends Thread{ArrayBlockingQueueString queue;//创建构造函数创建对象的时候进行赋值指定同一个阻塞队列public Cook(ArrayBlockingQueueString queue) {this.queue queue;}Overridepublic void run() {while (true){try {queue.put(面条);System.out.println(厨师做了一碗面条);} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}消费者
public class Customer extends Thread{ArrayBlockingQueueString queue;public Customer(ArrayBlockingQueueString queue) {this.queue queue;}Overridepublic void run() {while (true){try {String foodqueue.take();//tack底层也进行了加锁不需要我们自己定义System.out.println(获取食物food);} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}测试类
public class Test {public static void main(String[] args) {ArrayBlockingQueueString queuenew ArrayBlockingQueue(1);Customer customer new Customer(queue);Cook cook new Cook(queue);customer.setName(吃货);cook.setName(厨师);customer.start();cook.start();}
}