Java .notify()是';t notifying.wait()等待线程
我一直很难让等待的线程被通知 下面是调用Java .notify()是';t notifying.wait()等待线程,java,multithreading,Java,Multithreading,我一直很难让等待的线程被通知 下面是调用notify()的代码: public static void main(String[] args) { int endUsers = 0; Terminal terminal = new Terminal("Master"); ArrayList<Thread> threads = new ArrayList<Thread>(); threads.add(n
notify()
的代码:
public static void main(String[] args)
{
int endUsers = 0;
Terminal terminal = new Terminal("Master");
ArrayList<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(
new EndUser("EndUser 1", DEFAULT_DST_NODE, 50000, 50001),
"EndUser 1"));
endUsers++;
threads.add(new Thread(
new EndUser("EndUser 2", DEFAULT_DST_NODE, 50001, 50000),
"EndUser 2"));
endUsers++;
for (Thread t : threads)
{
t.start();
}
while (true)
{
int user = terminal.readInt("Which user is sending data? ");
if (user <= endUsers && user > 0)
{
synchronized (threads.get(user - 1))
{
threads.get(user - 1).notify();
}
}
}
}
}
public void run()
{
while (true)
{
try
{
synchronized (this)
{
this.wait();
}
this.send();
}
catch (Exception e)
{
}
}
}
我已经尝试了我能想到的一切,但我不知道为什么它不起作用
threads.get(user - 1).notify();
正在调用线程对象上的notify,其中
this.wait();
正在等待您的runnable或调用所在的类。
使用
应该解决你的问题
此外,我想提到的是,创建一个对象引用,然后等待并通知它,这将是一个功能齐全的方法,可以获得您想要的东西
您可以在thread类中将对象创建为(n)(可选静态)引用
public final (static) Object waitObject = new Object();
编辑:^制作此最终版本可防止其他(可能是恶意的)代码部分
从重新分配该值开始,这将使waitObject.notify()
方法是永远无法实现的
然后使用
waitObject.wait(); //or
waitObject.wait(time);
及
编辑:
正如@shmosel所指出的,在线程中使用“wait”、“sleep”或“notify”本质上是不安全的,如Java文档中所述。然而,尽管如此,该功能仍然可以使用,尽管不鼓励使用
对于其他Java参考,您可以使用多个资源;例如:
,(您可以将正在查找的内容附加到其中,例如“线程化,等待”搜索查询“安全Java实践线程化,等待”),等等。哪里定义了
run()
?您确定此
是一个线程
?顺便说一句,您永远不应该等待线程。这是在一个实现Runnablet的类中,这一点非常明显。您是否尝试过创建一个对象引用(对象o=新对象()),并使用它(o.wait()o.notify())?据我所知,这通常是有效的。您不应该在线程对象上使用wait/notify。看Javadoc.yes,它修复了它。非常感谢!很高兴我能帮忙。请不要忘记接受提供的答案。此外,如果能投赞成票,我们将不胜感激我不反对这种说法,也不鼓励OP这样做。但是,该声明没有回答OP提出的问题,因此与此无关。@shmosel,我包括了一些链接,并声明尝试的活动是不安全的做法。希望这对你来说足够好(不要粗鲁)
waitObject.wait(); //or
waitObject.wait(time);
waitObject.notify(); //or
waitObject.notifyAll();