如何在線程間通信中調用特定的線程?如何通知Java中的特定線程
在下面的程序我有兩個線程t1
和t2
。
當我打電話t1.notify()
它提出:
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Shared.methodTwo(NotifyThread.java:43)
at Thread2.run(NotifyThread.java:77)
Error
class Shared {
Thread1 t1 ;
Thread2 t2 ;
void ThreadInit(Thread1 t1 , Thread2 t2) {
this.t1 = t1 ;
this.t2 = t2 ;
}
synchronized void methodOne()
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+" is relasing the lock and going to wait");
try
{
wait(); //releases the lock of this object and waits
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(t.getName()+" got the object lock back and can continue with it's execution");
}
synchronized void methodTwo()
{
Thread t = Thread.currentThread();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
t1.notify();
System.out.println("A thread which is waiting for lock of this object is notified by "+t.getName());
}
}
class Thread1 extends Thread
{
Shared s ;
Thread1(Shared s) {
this.s = s ;
}
public void run()
{
s.methodOne(); //t1 calling methodOne() of 's' object
}
}
class Thread2 extends Thread {
Shared s ;
Thread2(Shared s) {
this.s = s ;
}
public void run()
{
s.methodTwo(); //t1 calling methodOne() of 's' object
}
}
public class NotifyThread
{
public static void main(String[] args)
{
final Shared s = new Shared();
Thread1 t1 = new Thread1(s) ;
Thread2 t2 = new Thread2(s) ;
s.ThreadInit(t1,t2) ;
t1.start();
t2.start();
}
}
但你不通知該線程。你在鎖上調用通知,它將通知委託給os調度程序,調度程序決定通知等待集中的哪個線程。我知道你知道的,但你所選擇的措詞似乎沒有說明什麼線程得到通知不是線程調用通知。這可能是OP所困惑的。 –
更好嗎? –
而這一切都說(這是相當不錯的建議)我不會使用等待/通知。我將使用'java.util.concurrent'包中的一些類:'Lock','Semaphore'和'CyclicBarrier' [所有更好的賭注](http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples /),而不是嘗試自己管理同步。 – markspace