Comment puis-je appeler un thread particulier dans la communication inter-thread?Comment notifier un thread spécifique en Java
Dans le programme ci-dessous, j'ai deux threads t1
et t2
.
Quand j'appelle t1.notify()
il soulève:
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();
}
}
Mais vous ne notifiez pas le thread. Vous appelez notifier sur le verrou et il délègue la notification au planificateur d'OS, et le planificateur décide quel thread dans l'ensemble d'attente est notifié. Ce que je sais que vous savez, mais votre formulation choisie semble ne pas faire un point important que ce sujet est notifié n'est pas à la demande d'avis de thread. Ce qui peut être ce que le PO est confus. –
Est-ce mieux? –
Et tout ce qui est dit (ce qui est un conseil assez décent) je ne voudrais pas utiliser wait/notify du tout. J'utiliserais certaines classes du paquet 'java.util.concurrent':' Lock', 'Semaphore' et' CyclicBarrier' sont [tous de meilleurs paris] (http://winterbe.com/posts/2015/04/30/java8-concurrence-tutorial-synchronized-locks-examples /) plutôt que d'essayer de gérer vous-même la synchronisation. – markspace