Odeberte kód, který volá vlákno suspend/resume.
Použijte poskytnutý 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!" );
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();
}
|
|