线程超时释放

如果线程池线程资源耗尽,而线程又不释放,无疑是很严重的问题。
思路:
1.newFixedThreadPool 的Future类get方法可以设置超时时间,接口get是在给定时间完成,否则throws 超时异常。

   /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

2.自己写监控线程,demo如下:

package filesearch;

public class StopTest {
	public static void main(String[] args) {
		int i = 1;
		/**
		 * 具体任务在该线程完成
		 * ---args--- 传入所需参数
		 */
		WorkThread ct = new StopTest().new WorkThread("---args---");
		ct.start();
		/**
		 * 工作线程没执行完,计算时间:
		 * 1)超时,工作线程stop,循环break,流程结束
		 * 2)线程执行完,while循环结束,流程结束
		 */
		while(ct.isAlive()){
			i++;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(""+i);
			if(i>10){
				ct.stop();
				break;
			}
		}
		
	}
	class WorkThread extends Thread {
		String str ;
		WorkThread(String str1){str=str1;}
		public void run() {
			try {
				System.out.println("arg:"+str);
				System.out.println("begin");
				Thread.sleep(8000);
				System.out.println("end");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值