java - 为什么我的线程没有收到通知?

标签 java multithreading scjp

练习中

Make a program where you have a fashion and a sewing machine, so the Operator enter data width and height, notify the sewing machine in order to perform their job.

Operator 接收数据并处理并通知机器。 Machine 接收数据并完成处理。

但是,当我运行时,Maquina 线程没有收到通知,机器和 Operator 处于无限循环中接收数据。

public class Operator extends Thread {

    Scanner in = new Scanner(System.in);
    int altura, largura;
    public void run() {
        while(true) {
            synchronized (this) {
                System.out.print("Altura: ");
                altura = in.nextInt();
                System.out.print("Largura: ");
                largura = in.nextInt();
                notify();
            }
        }
    }

    public String getForma() {
        return "Forro de mesa : " + (altura * largura);
    }
}

public class Maquina extends Thread{

    private Operator c;

    public Maquina(Operator c) {
        this.c = c;
    }


    public void run() {
        while(true) {
            synchronized (c) {
                try {

                    System.out.println("Waiting shape...");
                    c.wait();

                    System.out.println("init drawn...");
                    Thread.currentThread().sleep(3000);

                    System.out.println("drawing...");
                    Thread.currentThread().sleep(3000);

                    System.out.println(c.getForma() + ", finalized");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

最佳答案

在运行您的代码时,问题似乎是永远不会到达 "Waiting shape..." 消息。这让我感到惊讶,但似乎 while (true) { synchronized(c) 永远不会让 Maquina 进入 synchronized block 。

Operator.run() 方法的前面添加一个小 sleep 可以解决这个问题。它为 Maquina 获取锁并进入 wait() 提供了时间。

while (true) {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return;
    }
    synchronized (this) {
        System.out.print("Altura: ");
        altura = in.nextInt();
        System.out.print("Largura: ");
        largura = in.nextInt();
        notify();
    }
}

关于java - 为什么我的线程没有收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17949317/

相关文章:

java - 将上传的文件保存在磁盘、ubuntu 路径上

java - Hibernate - 我可以混合命名参数和位置参数吗?

java - Icefaces 2 插件问题

c# - 使静态类中的字典成为线程安全的?

c# - 在一个线程中引发事件以在第二个线程中调用方法

java - instanceof 运算符在原始和包装器类型数组的情况下

java - Queue 接口(interface)中的 peek() 方法

java - JDOM 中的命名空间(默认)

c# - 在多个线程中将 Stream 读取到 MemoryStream

java - SCJP 问题 : Method ambiguous