java 多线程 超时_【Java】Java多线程任务超时结束的5种实现方法

方法一:使用Thread.join(long million)

(先讲一下本人对join方法的理解,已理解此方法的可以略过)join方法可以这样理解,在理解它之前,先解释另一个常识,即当前线程(后面称为目标线程,因为它是我们想使其超时结束的目标任务)的创建及start的调用,一定是在另一个线程中进行的(最起码是main线程,也可以是不同于main线程的其他线程),这里我们假设为main线程,并且称之为依赖线程,因为目标线程的创建是在他里面执行的。介绍完这些常识就可以进一步解释了,join的字面意思是,使目标线程加入到依赖线程中去,也可以理解为在依赖线程中等待目标线程一直执行直至结束(如果没有设置超时参数的话)。设置了超时参数(假设为5秒)就会这样执行,在依赖线程中调用了join之后,相当于告诉依赖线程,现在我要插入到你的线程中来,即两个线程合二为一,相当于一个线程(如果不执行插入的话,那目标线程和依赖线程就是并行执行),而且目标线程是插在主线程前面,所以目标线程先执行,但你主线程只需要等我5秒,5秒之后,不管我有没有执行完毕,我们两都分开,这时又会变成两个并行执行的线程,而不是目标线程直接结束执行,这点很重要。

其实这个方法比较牵强,因为它主要作用是用来多个线程之间进行同步的。但因为它提供了这个带参数的方法(所以这也给了我们一个更广泛的思路,就是一般带有超时参数的方法我们都可以尝试着用它来实现超时结束任务),所以我们可以用它来实现。注意这里的参数的单位是固定的毫秒,不同于接下来的带单位的函数。具体用法请看示例:

public classJoinTest {public static voidmain(String[] args) {

Task task1= new Task("one", 4);

Task task2= new Task("two", 2);

Thread t1= newThread(task1);

Thread t2= newThread(task2);

t1.start();try{

t1.join(2000); //在主线程中等待t1执行2秒

} catch(InterruptedException e) {

System.out.println("t1 interrupted when waiting join");

e.printStackTrace();

}

t1.interrupt();//这里很重要,一定要打断t1,因为它已经执行了2秒。

t2.start();try{

t2.join(1000);

}catch(InterruptedException e) {

System.out.println("t2 interrupted when waiting join");

e.printStackTrace();

}

}

}class Task implementsRunnable {publicString name;private inttime;public Task(String s, intt) {

name=s;

time=t;

}public voidrun() {for (int i = 0; i < time; ++i) {

System.out.println("task " + name + " " + (i + 1) + " round");try{

Thread.sleep(1000);

}catch(InterruptedException e) {

System.out.println(name+ "is interrupted when calculating, will stop...");return; //注意这里如果不return的话,线程还会继续执行,所以任务超时后在这里处理结果然后返回

}

}

}

}

在主线程中等待t1执行2秒之后,要interrupt(而不是直接调用stop,这个方法已经被弃用)掉它,然后在t1里面会产出一个中断异常,在异常里面处理完该处理的事,就要return,一定要return,如果不return的话,t1还会继续执行,只不过是与主线程并行执行。

方法二:Future.get(long million, TimeUnit unit) 配合Future.cancle(true)

Future系列(它的子类)的都可以实现,这里采用最简单的Future接口实现。

public classFutureTest {static class Task implements Callable{publicString name;private inttime;public Task(String s, intt) {

name=s;

time=t;

}

@Overridepublic Boolean call() throwsException {for (int i = 0; i < time; ++i) {

System.out.println("task " + name + " round " + (i + 1));try{

Thread.sleep(1000);

}catch(InterruptedException e) {

System.out.println(name+ " is interrupted when calculating, will stop...");return false; //注意这里如果不return的话,线程还会继续执行,所以任务超时后在这里处理结果然后返回

}

}return true;

}

}public static voidmain(String[] args) {

ExecutorService executor=Executors.newCachedThreadPool();

Task task1= new Task("one", 5);

Future f1 =executor.submit(task1);try{if (f1.get(2, TimeUnit.SECONDS)) { //future将在2秒之后取结果

System.out.println("one complete successfully");

}

}catch(InterruptedException e) {

System.out.println("future在睡着时被打断");

executor.shutdownNow();

}catch(ExecutionException e) {

System.out.println("future在尝试取得任务结果时出错");

executor.shutdownNow();

}catch(TimeoutException e) {

System.out.println("future时间超时");

f1.cancel(true);//executor.shutdownNow();//executor.shutdown();

} finally{

executor.shutdownNow();

}

}

}

运行结果如下,task在2秒之后停止:

5cbc9d265d0682f46eb5b36106eadce6.png

如果把Task中捕获InterruptedException的catch块中的return注释掉,就是这样的结果:

6d8a2d6dc3f77ce7e00849092f0dc467.png

task继续执行,直至结束

方法三:ExecutorService.awaitTermination(long million, TimeUnit unit)

这个方法会一直等待所有的任务都结束,或者超时时间到立即返回,若所有任务都完成则返回true,否则返回false

public classAwaitTermination {static class Task implementsRunnable {publicString name;private inttime;public Task(String s, intt) {

name=s;

time=t;

}public voidrun() {for (int i = 0; i < time; ++i) {try{

Thread.sleep(1000);

}catch(InterruptedException e) {

System.out.println(name+ " is interrupted when calculating, will stop...");return; //注意这里如果不return的话,线程还会继续执行,所以任务超时后在这里处理结果然后返回

}

System.out.println("task " + name + " " + (i + 1) + " round");

}

System.out.println("task " + name + " finished successfully");

}

}public static voidmain(String[] args) {

ExecutorService executor=Executors.newCachedThreadPool();

Task task= new Task("one", 5);

Task task2= new Task("two", 2);

Future> future =executor.submit(task);

Future> future2 =executor.submit(task2);

List> futures = new ArrayList>();

futures.add(future);

futures.add(future2);try{if (executor.awaitTermination(3, TimeUnit.SECONDS)) {

System.out.println("task finished");

}else{

System.out.println("task time out,will terminate");for (Future>f : futures) {if (!f.isDone()) {

f.cancel(true);

}

}

}

}catch(InterruptedException e) {

System.out.println("executor is interrupted");

}finally{

executor.shutdown();

}

}

}

运行结果如下:

a1ba7e278a1791b50ffeff947ccacc98.png

方法四:设置一个守护线程,守护线程先sleep一段定时时间,睡醒后打断它所监视的线程

public classDemonThread {static class Task implementsRunnable {privateString name;private inttime;public Task(String s, intt) {

name=s;

time=t;

}public intgetTime() {returntime;

}public voidrun() {for (int i = 0; i < time; ++i) {try{

Thread.sleep(1000);

}catch(InterruptedException e) {

System.out.println(name+ " is interrupted when calculating, will stop...");return; //注意这里如果不return的话,线程还会继续执行,所以任务超时后在这里处理结果然后返回

}

System.out.println("task " + name + " " + (i + 1) + " round");

}

System.out.println("task " + name + " finished successfully");

}

}static class Daemon implementsRunnable {

List tasks = new ArrayList();privateThread thread;private inttime;public Daemon(Thread r, intt) {

thread=r;

time=t;

}public voidaddTask(Runnable r) {

tasks.add(r);

}

@Overridepublic voidrun() {while (true) {try{

Thread.sleep(time* 1000);

}catch(InterruptedException e) {

e.printStackTrace();

}

thread.interrupt();

}

}

}public static voidmain(String[] args) {

Task task1= new Task("one", 5);

Thread t1= newThread(task1);

Daemon daemon= new Daemon(t1, 3);

Thread daemoThread= newThread(daemon);

daemoThread.setDaemon(true);

t1.start();

daemoThread.start();

}

}

一开始准备在守护任务里面用一个集合来实现监视多个任务,接着发现要实现这个功能还得在这个守护任务里面为每一个监视的任务开启一个监视任务,一时又想不到更好的方法来解决,索性只监视一个算了,留待以后改进吧。

运行结果如下:

d23fcd5a16569dfce359ab446ba233b6.png

方法五:使用Timer / TimerTask,或其他schedule定时相关的类

总结:需要注意的是,无论以上哪一种方法,其实现原理都是在超时后通过interrupt打断目标线程的运行,所以都要在捕捉到InterruptedException的catch代码块中return,否则线程仍然会继续执行。另外,最后两种方法本质上是一样的,都是通过持有目标线程的引用,在定时结束后打断目标线程,这两种方法的控制精度最低,因为它是采用另一个线程来监视目标线程的运行时间,因为线程调度的不确定性,另一个线程在定时结束后不一定会马上得到执行而打断目标线程。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值