线程超时释放

如果线程池线程资源耗尽,而线程又不释放,无疑是很严重的问题。
思路:
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();
			}
		}
	}

}


你可能感兴趣的:(并发)