【问题标题】:Simple thread program to understand synchronized, wait and notify理解同步、等待和通知的简单线程程序
【发布时间】:2021-04-08 20:57:09
【问题描述】:

我在这里和其他网站上查看其他示例,但我不明白我做错了什么。我正在尝试做一个程序,一个线程将对象的值设置为值 1 到 10,但我想等待它更改值,直到其他线程读取它,所以我可以打印它们并有一个列表从 1 到 10。

我的 readThread 运行方法只是从 1 循环到 10 调用以下方法:

private synchronized int receive() {
    try {
        wait();
        int value = this.mainThread.getValor();
        notify();
        return value;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return -1;  
}

我的 writeThread 运行方法只是从 1 循环到 10 调用以下方法:

private synchronized void send(int n) {
    try {
        this.mainThread.setValor(n);
        notify();
        wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

主要方法如下:

public static void main(String[] args) {
    MainThread mt = new MainThread();
    ReadThread rt = new ReadThread(mt);
    WriteThread wt = new WriteThread(mt);
    
    wt.start();
    rt.start();

}

MainThead 类具有使用其 getter 和 setter 定义的属性“valor”

感谢您的帮助

【问题讨论】:

  • 正如汤姆在下面提到的,有很多潜在的问题。就代码而言,它是生产者消费者问题的一个很好的例子。我看到的主要缺失是无法判断何时生成(写入)值以及何时消耗(读取)值。如果你添加,我认为你会得到它的工作。

标签: java multithreading synchronization


【解决方案1】:

有几个明显的问题。

看起来好像您在同一个锁上进行同步(没有足够的代码可以 100% 确定)。一般来说,您应该创建一个专门用作锁的对象。

send 可以在receive 之前执行。在这种情况下,第一个 notify 将什么也不做,两个线程都将在 wait 中停止。

理论上,不能保证wait 不会自发唤醒。出于这个和其他原因,您真的希望 waitwhile 循环中。

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多