问题补充:
yx200404 写道
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class A {
//自己设置大小,这里设置的是一个单工作线程
final ExecutorService exec = Executors.newSingleThreadExecutor();
public void send() {
TaskThread taskThread = new TaskThread();
Future taskFuture = exec.submit(taskThread);
try {
//此处看任务线程是否返回值,如果不返回,那么在1分钟后任务线程会被强行终止
taskFuture.get(1, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
//
} catch (ExecutionException ex) {
//
} catch (TimeoutException ex) {
//
} finally {
}
}
class TaskThread implements Callable {
public Object call() throws Exception {
methodA();
methodB();
methodC();
methodD();
methodE();
return false;
}
}
}
哥们些,什么年代了...还在自己搞"终止"处理~
public class StopThreadTest {
//自己设置大小,这里设置的是一个单工作线程
private static boolean isTO = false;
final ExecutorService exec = Executors.newSingleThreadExecutor();
public void send() {
TaskThread taskThread = new TaskThread();
Future taskFuture = exec.submit(taskThread);
try {
//此处看任务线程是否返回值,如果不返回,那么在1分钟后任务线程会被强行终止
System.err.println("taskResult:" + taskFuture.get(5, TimeUnit.SECONDS));
System.err.println("taskStat:" + taskFuture.isCancelled());
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (TimeoutException ex) {
ex.printStackTrace();
isTO = true;
} finally {
}
}
public static void main(String[] args) {
new StopThreadTest().send();
}
class TaskThread implements Callable {
public Object call() throws Exception {
for (int i = 0; i < 100000000; i++) {
if (i % 100 == 0)
i -= 50;
if (isTO)
System.out.println(i);
}
return true;
}
}
}
为什么5秒后超时了任务线程还一直在运行??任务线程怎么终止了??这只是超时。