本文共 1395 字,大约阅读时间需要 4 分钟。
多线程:sleep(),线程处于就绪状态,CPU执行其他线程,该线程的监控状态依然保持着,且不会释放对象锁。notify()线程会放弃对象锁。
class Meal {
private final int orderNum;
public Meal(int orderNum){
this.orderNum = orderNum;
}
}
class WaitPeople implements Runnable {
private Restaurant restaurant;
public void run() {
try{
while(!Thread.interrupted()){
synchronized(this){
while(restaurant.meal == null){
wait();
}
System.out.println("wait people got " + restaurant.meal);
synchronized(restaurant.chef) {
restaurant.meal = null;
restarurant.chef.notifyAll();
}
}
}
}catch(InterrupedException e) {
System.out.println("Wait person interrupted");
}
}
}
class Chef implements Runnable {
private Restaurant restaurant;
private int count = 0;
public Chef(Restarurant restaurant){
this.restaurant = restaurant;
}
public void run(){
try{
synchronized(this){
while(!Thread.interupted()){
wait();
}
if(++ count == 10){
restaurant.exec.showdownNow();
}
System.out.println("order up"):
synchronized(restaurant.waitpeople){
restaurant.mean = new Meal(count);
restaurant.waitpeople.notifyAll();
}
}
TimeUnit.MILLISECONDS.sleep(100);
}catch(InterruptedException e){
}
}
}
public class Restaurant {
Meal meal;
ExecutorService exec = Exectors.newCachedThreadPool();
Chef chef = new Chef(this);
WaitPerson waitpeople = new WaitPerson(this):
public Restaurant(){
exec.execute(chef);
exec.execute(waitpeople);
}
public static void main(String[] args){
new Restaurant();
}
}
转载地址:https://blog.csdn.net/weixin_32467749/article/details/114561066 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!