Если такой функционал нужен, то его нужно реализовывать через флаги.
public class App extends Thread {
static App self;
private volatile boolean threadSuspended = false;
public App(String name) {
super(name);
}
public static void main(String[] args) {
self = new App("WORKER");
self.start();
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
printFromThread("Let's suspend!");
self._suspend();
Thread.sleep(5000);
printFromThread("Let's resume!");
self._resume();
Thread.sleep(15000);
printFromThread("Let's stop!");
self._stop();
Thread.sleep(15000);
printFromThread("I'm going to die...");
} catch (InterruptedException e) {
printFromThread("Interrupter is interrupted!!!))))))))))))))))))");
}
}
}, "controller").start();
}
private static void printFromThread(String x) {
System.out.println( "[ " + Thread.currentThread().getName() + " (" + System.nanoTime() + ") ]" + x);
}
public void run() {
Thread thisThread = Thread.currentThread();
while (self == thisThread) {
try {
printFromThread("I'm starting sleeping");
Thread.sleep(1000);
printFromThread("I've just finished sleeping");
synchronized (this) {
printFromThread("I'm just synchronized");
while (threadSuspended && self == thisThread) {
printFromThread("Let's start waiting iteration");
this.wait();
printFromThread("Good morning!.....");
}
}
} catch (InterruptedException e) {
printFromThread("Look's like I was awoken now!");
}
repaint();
}
}
public void repaint() {
printFromThread("<<<<<<<<<<<<<<<<<<< Repainting ... >>>>>>>>>>>>>>>>>>>>>>");
}
public synchronized void _suspend() {
printFromThread("self was suspended.");
threadSuspended = true;
}
public synchronized void _resume() {
printFromThread("self was resumed");
threadSuspended = false;
notify();
}
public synchronized void _stop() {
self = null;
printFromThread("self was \"nulled\". So let's notify to break wait");
notify();
}
}
Комментариев нет:
Отправить комментарий