Exemple

public static final Boolean lock = Boolean.TRUE;
public static boolean runCond = true;

public static void main( String[] args ) {
Runnable runnable = new Runnable() {
public void run() {
synchronized ( lock ) {
while ( runCond ) {
System.out.println( "Hello World!" ); //$NON-NLS-1$
try { wait( 1000 ); } catch (InterruptedException e) {}
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
thread.suspend();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
thread.resume();
runCond = false;
}
Solution
Supprimez le code appelant l'unité d'exécution suspend/resume.
Utilisez SuspendSafeRunnable.

public static abstract class SuspendSafeRunnable extends StopSafeRunnable {
public void doRun() {
checkForPause();
doWork();
}
public void suspend() {
synchronized ( lock ) {
suspended = true;
lock.notifyAll();
}
}
public void resume() {
synchronized ( lock ) {
suspended = false;
lock.notifyAll();
}
}
public boolean isPaused() {
return suspended;
}
protected abstract void doWork();

private void checkForPause() {
synchronized ( lock ) {
while ( suspended ) {
try {
lock.wait();
} catch (InterruptedException e) {}
}
}
}
private boolean suspended = false;
private Object lock = new Object();
}

public static void main( String[] args ) {
SuspendSafeRunnable runnable = new SuspendSafeRunnable() {
public void doWork() {
System.out.println( "Hello World!" ); //$NON-NLS-1$
try { Thread.sleep( 1000 ); } catch (InterruptedException e) {}
}
};
Thread thread = new Thread(runnable);
thread.start();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
runnable.suspend();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
runnable.resume();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
runnable.stop();
}