스레드 간 통신에서 특정 스레드를 어떻게 호출 할 수 있습니까?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