您可以使用阻塞队列在工作线程和主线程之间进行通信,例如
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
Thread t1 = new Thread(new A(queue));
t1.start();
if(queue.take().equals("Started A")) {
Thread t2 = new Thread(new B(queue));
t2.start();
Thread t3 = new Thread(new C());
t3.start();
}
if(queue.take().equals("Started B")) {
Thread t4 = new Thread(new D());
t4.start();
}
}
public class A implements Runnable {
private BlockingQueue queue;
private volatile boolean isCancelled = false;
public A(BlockingQueue queue) {
this.queue = queue;
}
public void cancel() {
isCancelled = true;
}
public void run() {
// initialization code
queue.offer("Started A");
while(!isCancelled) {
...
}
queue.offer("Stopped A");
}
}
使用类似的逻辑来停止线程(在服务中使用while(!isCancelled)
循环,并在cancel()
需要停止服务时让主线程调用服务)。