要使用wait()
您必须拥有显示器。
您通过使用获得所有权synchronize
。在你的情况下synchronize(this)
。
但是要阻止 3 个线程并从第 4 个线程释放它们,您可以使用java.util.concurrent.CyclicBarrier
或Perceptionjava.util.concurrent.CountDownLatch
提到的
这是一个带有 CyclicBarrier 的版本:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class RendezVous extends Thread {
private final CyclicBarrier _barrier;
RendezVous( String name, CyclicBarrier barrier ) {
super( name );
_barrier = barrier;
setDaemon( true );
start();
}
@Override public void run() {
System.out.println( getName() + " waits for counterparts..." );
try { _barrier.await(); }
catch( InterruptedException | BrokenBarrierException x ) {
x.printStackTrace(); }
System.out.println( getName() + " has reached its rendez-vous!");
}
public static void main( String[] args ) throws InterruptedException {
CyclicBarrier barrier = new CyclicBarrier( 4 );
new RendezVous( "Rdvz 1", barrier ); Thread.sleep( 1000L );
new RendezVous( "Rdvz 2", barrier ); Thread.sleep( 1000L );
new RendezVous( "Rdvz 3", barrier ); Thread.sleep( 1000L );
new RendezVous( "Rdvz 4", barrier ); Thread.sleep( 10000L );
}
}
输出:
Rdvz 1 waits for counterparts...
Rdvz 2 waits for counterparts...
Rdvz 3 waits for counterparts...
Rdvz 4 waits for counterparts...
Rdvz 4 has reached its rendez-vous!
Rdvz 1 has reached its rendez-vous!
Rdvz 2 has reached its rendez-vous!
Rdvz 3 has reached its rendez-vous!
还有一个带有 CountDownLatch 的版本:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo extends Thread {
private final CountDownLatch _cdl;
CountDownLatchDemo( String name, CountDownLatch cdl ) {
super( name );
_cdl = cdl;
setDaemon( true );
start();
}
@Override public void run() {
System.out.println( getName() + " waits for counterparts..." );
try {
_cdl.countDown();
_cdl.await();
}
catch( InterruptedException x ) {
x.printStackTrace(); }
System.out.println( getName() + " has reached its rendez-vous!");
}
public static void main( String[] args ) throws InterruptedException {
CountDownLatch cdl = new CountDownLatch( 4 );
new CountDownLatchDemo( "Rdvz 1", cdl ); Thread.sleep( 1000L );
new CountDownLatchDemo( "Rdvz 2", cdl ); Thread.sleep( 1000L );
new CountDownLatchDemo( "Rdvz 3", cdl ); Thread.sleep( 1000L );
new CountDownLatchDemo( "Rdvz 4", cdl ); Thread.sleep( 10000L );
}
}
输出:
Rdvz 1 waits for counterparts...
Rdvz 2 waits for counterparts...
Rdvz 3 waits for counterparts...
Rdvz 4 waits for counterparts...
Rdvz 4 has reached its rendez-vous!
Rdvz 1 has reached its rendez-vous!
Rdvz 2 has reached its rendez-vous!
Rdvz 3 has reached its rendez-vous!