java - Java 中的多线程

标签 java multithreading

我是编程新手,所以我决定编写一个简单的多线程程序。它展示了餐厅的工作情况。顾客点菜,服务员上菜,厨师准备食物。但我有一个问题,我认为这是死锁的情况,因为当我运行它时,它打印“排序”而没有其他内容。我不明白出了什么问题。请帮忙。谢谢。

餐厅.java

public class Restaurant implements Runnable{
 Client cl=new Client();
 Chef ch=new Chef();
 Waiter w=new Waiter();

public synchronized void makeOrder() throws InterruptedException{
notifyAll();
cl.makeOrder();
wait();

}   

public synchronized void makeServing() throws InterruptedException{

notifyAll();
wait();

}

public synchronized void makeFood() throws InterruptedException{
notifyAll();
ch.makeFood();
Thread.sleep(1000);
wait();
}

@Override
public void run() {
    try {
    for(int i=0;i<10;i++){
        makeOrder();
        makeServing();
        makeFood();
    }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

客户端.java

public class Client{
public void makeOrder(){
System.out.println("Ordering"+Thread.currentThread().getId());
}

服务员.java

public class Waiter {

public void makeServe() {
    System.out.println("Serving order"+Thread.currentThread().getId());

}

厨师.java

public class Chef {

public void makeFood(){

    System.out.println("Making food "+Thread.currentThread().getId());

}

Main.java

public class Main {
public static void main(String[] args) {

    Restaurant r=new Restaurant();
    Thread t=new Thread(r);
    t.start();
}

}

最佳答案

当您在 Restaurant 线程中调用 makeOrder(); 时,它将 wait()。然后就什么都不会发生了。问题是,你只有一个线程,这个线程无法通知自己。我认为你想要做的是将你的 Client、Waiter 和 Chef 变成线程。然后一个接一个地启动它们,然后服务员必须等到客户下订单,厨师必须等到服务员收到订单......

如果您在 google 上搜索“java 生产者消费者示例”,您可能会找到一些有用的示例。

关于java - Java 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383312/

相关文章:

java - onBackPressed() 最佳实践/性能

java - 生成 N x N 网格

java - executorThreadPool 检查任务何时完成或超时到期

java - volatile关键字没有用 当使用synchronized时?

用于嵌套函数调用的 Java 正则表达式

java - spring-boot:mockito忽略测试标准并返回通过的测试

java - 如何在知道日期的 CalendarView 中将焦点设置在特定日期是 "dd/mm/yyyy"

multithreading - ViewModel 和多线程最佳实践

.net - 类库中的 WebBrowser 控件

C++11 原子类和操作——我说得对吗