java 线程强制停止线程_java中如何强制停止线程?

问题补充:

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秒后超时了任务线程还一直在运行??任务线程怎么终止了??这只是超时。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值