gpt4 book ai didi

Java等待并通知: IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-12-01 18:12:45 26 4
gpt4 key购买 nike

我不完全理解waitnotify(Object)是如何工作的,结果我被迫瘦身将我的尝试记入以下代码部分。

Main.java:

import java.util.ArrayList;

class Main
{
public static Main main = null;

public static int numRunners = 4;
public static ArrayList<Runner> runners = null;

public static void main(String[] args)
{
main = new Main();
}

Main()
{
runners = new ArrayList<Runner>(numRunners);

for (int i = 0; i < numRunners; i++)
{
Runner r = new Runner();
runners.add(r);
new Thread(r).start();
}

System.out.println("Runners ready.");
notifyAll();
}
}

Runner.java:

class Runner implements Runnable
{
public void run()
{
try
{
Main.main.wait();
} catch (InterruptedException e) {}
System.out.println("Runner away!");
}
}

目前,我在调用 Main.main.wait(); 时收到 IllegalMonitorStateException,但我不明白为什么。据我所知,我需要同步 Runner.run,但这样做时我假设它只会通知一个线程,而我的想法是通知所有线程。

我查看了java.util.concurrent,但找不到合适的替代品(也许我只是错过了一些东西)。

最佳答案

除非当前线程拥有该对象的监视器,否则您无法在对象上wait()。为此,您必须对其进行同步:

class Runner implements Runnable
{
public void run()
{
try
{
synchronized(Main.main) {
Main.main.wait();
}
} catch (InterruptedException e) {}
System.out.println("Runner away!");
}
}

同样的规则也适用于 notify()/notifyAll()

Javadocs for wait()提到这一点:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

来自 notify() :

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

关于Java等待并通知: IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60435779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com