如果線程池線程資源耗盡,而線程又不釋放,無疑是很嚴重的問題。
思路:
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();
}
}
}
}