我希望我的主线程在给定事件时通知另一个线程,但不要暂停自己。 另一个线程是一个无限循环,我需要它在每次迭代后等待,直到主线程再次唤醒它。
这似乎排除了wait / notify模式,因为它会暂停在共享监视器上调用notify的线程。我也考虑过CyclicBarrier,但我不希望主线程调用Barrier.await,并等到另一个线程调用Barrier.await,因为它可能需要很长时间......
有什么想法吗?谢谢!
答案 0 :(得分:0)
使等待的线程像这样:
class MyThread extends Thread() {
private volatile boolean go;
public void wakeUpBuddy() {
go=true;
synchronized(this) {
notify();
}
}
public void run() {
while(!interrupted()) {
// some work before wait
synchronized(this) {
while(!go) {
wait();
}
go = false;
}
// some work after release
}
}
}
然后从主线程调用MyThread.wakeUpBuddy()的实例;它将通过一次并等待另一个电话。
答案 1 :(得分:0)
如何使用Observer模式?
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.TimeUnit;
public class Main extends Observable {
public static void main(String... args) {
final MyThread t = new MyThread();
final Main m = new Main();
m.addObserver(t);
// start the thread
t.start();
for (int i = 0; i < 25; i++) {
if (i % 5 == 0) { // event received?
m.setChanged();
m.notifyObservers(i);
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (Exception ex) {
}
}
}
}
class MyThread extends Thread implements Observer {
private boolean wait = true;
@Override
public void run() {
while (true) {
while (wait) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException ex) {
// interrupted
}
}
System.out.println("I am invoked ..");
wait = true;
}
}
@Override
public void update(Observable o, Object arg) {
System.out.println("Update received .. " + arg);
wait = false;
}
}