线程超时控制的一种方法

 原理:增加一个线程类用于监控目标类即可,代码如下:

package aa;

import java.util.Vector;

public class SomeoneThread extends Thread implements ISomeoneThread{
 /**
  * @param args
  */
 public static void main(String[] args) {
  SomeoneThread thread = new SomeoneThread();
  thread.start();
  
  TimeoutManager manager = new TimeoutManager();
  manager.vector.add(thread);
  manager.start();

 }
 
 @Override
 public void run() {
  super.run();
  startTime = System.currentTimeMillis();
  int i = 0;
  while(isRunning()){
   System.out.println("vlaue:" + i++ );
   
   try {
    Thread.currentThread().sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  
 }
 // 运行标识
 private boolean running = true;

 // 目标类的启动时间
 private long startTime;
 
 public boolean timeout() {
  long currentTime = System.currentTimeMillis();
  // 表示当运行超时,例如10s
  if ( (currentTime - startTime) < 10000 ){
   return false;
  }
  return true;
 }

 public synchronized boolean isRunning() {
  return running;
 }

 public synchronized void setRunning(boolean running) {
  this.running = running;
 }
 
}


class TimeoutManager extends Thread {

 public Vector vector = new Vector();
 
 public boolean running = true;
 
 @Override
 public void run() {
  super.run();
  while(running){
   for ( int i = 0; i< vector.size();i++){
    Object obj = vector.get(i);
    if ( obj instanceof ISomeoneThread){
     if ( ((ISomeoneThread)obj).timeout()){
      ((SomeoneThread)obj).setRunning(false);
      System.out.println("timeout");
      running = false;
     }
    }
   }
  }
 }
 
}

interface ISomeoneThread {
 public boolean timeout();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线程超时退出是指当一个线程的执行时间超过了预定的时间限制时,线程会自动退出或被强制终止。 在多线程编程中,有时候我们需要限制线程的执行时间,以避免线程的无限等待或导致整个程序的阻塞。为了实现线程超时退出的功能,我们可以采取以下几种方式: 1. 使用定时器:可以在创建线程之后启动一个定时器,在规定时间内检查线程的状态,如果超过了设定的时间限制,就强制终止线程的执行。 2. 使用Thread类提供的join()方法:join()方法允许一个线程等待另一个线程执行完毕。我们可以在创建线程之后,调用join()方法,并设置一个超时时间,如果在超时时间内线程未执行完毕,则认为线程超时退出。 3. 使用信号量或锁机制:可以在创建线程之前设置一个信号量或锁,当线程超时退出时,通过释放或获取信号量或锁来终止线程的执行。 无论采取哪种方式,我们在线程超时退出时,需要注意线程的资源释放和状态的处理。比如,我们可以在线程超时退出时,手动释放线程所占用的资源,如关闭文件、释放内存等;或者可以记录线程超时退出的次数,以便在后续处理中做相应的处理。同时,我们也应该注意避免线程超时退出对整个程序的影响,比如通过设置合理的超时时间、合理分配资源等方式来提高程序的健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值