这是最终的分析......用于杀死线程。
使用线程来控制程序 B 的执行。但是不允许通过线程停止进程,因为相关方法已被弃用(停止/暂停等)
使用 ThreadGroup(只有一个线程作为其成员)并在组上调用“销毁”。但它再次落在同一轨道上,因为在尝试销毁操作之前应该停止每个线程。
Process/ProcessBuilder via Runtime 似乎是获取进程引用并调用destroy()、waitFor() 等的更好方法,正如用户@Tudor提到的那样。
这是我尝试过的确切概述的代码,它无法杀死,注释行 while(isValid()) 代表我的另一个 java 程序调用。
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
class TaskWorker implements Callable {
private final int number;
public TaskWorker(int number) {
this.number = number;
}
public Boolean call() throws InterruptedException {
while (!Thread.currentThread().isInterrupted()) {
myBusyFunction();
}
return true;
}
private boolean isValid() {
return true;
}
private void myBusyFunction() {
//while (isValid()) {
System.out.println(number + ">....Working.....");
//}
}
}
public class Test {
public static void main(final String[] args) {
CompletionService cs = new ExecutorCompletionService(Executors.newFixedThreadPool(1));
Collection tasks = new ArrayList(10);
tasks.add(new TaskWorker(1));
List> futures = new ArrayList>(tasks.size());
try {
for (Callable task : tasks) {
futures.add(cs.submit(task));
}
//----
for (int t = 0; t result = cs.poll(10, TimeUnit.SECONDS);
if (result == null) {
System.out.println(new Date() + ":Worker Timedout:");
//So lets cancel the first futures we find that havent completed
for (Future future : futures) {
System.out.println("Checking future");
if (future.isDone()) {
continue;
} else {
future.cancel(true);
System.out.println("Cancelled");
break;
}
}
continue;
} else {
try {
if (result.isDone() && !result.isCancelled() && result.get()) {
System.out.println(new Date() + ":Worker Completed:");
} else if (result.isDone() && !result.isCancelled() && !result.get()) {
System.out.println(new Date() + ":Worker Failed");
}
} catch (ExecutionException ee) {
ee.printStackTrace(System.out);
}
}
}
} catch (InterruptedException ie) {
} finally {
//Cancel by interrupting any existing tasks currently running in Executor Service
for (Future f : futures) {
f.cancel(true);
}
}
System.out.println(new Date() + ":Done");
}
}