线程超时

  1. //    SearchThread.java  
  2. class SearchThread extends Thread {  
  3.        private List result = new ArrayList();  
  4.        private boolean success_flag = false;  
  5.        ...........  
  6.   
  7.        public SearchThread(xxxx,xxxxx) {  
  8.             .......  
  9.        }  
  10.   
  11.        public void run() {  
  12.              this.result = API.getSearchResult(xxxx,xxxx,xxxx);  
  13.              this.success_flag = true;  
  14.        }  
  15.  
  16.        public List getResults() {  
  17.              return this.result;  
  18.        }  
  19.   
  20.        public boolean isSuccess() {  
  21.              return this.success_flag;  
  22.        }  
  23. }  
  1. //  XXXAction.java  
  2. ...........  
  3. SearchThread thread = new SearchThread(xxxxxx,  xxxxxxx);  
  4. thread.start();  
  5. try {  
  6.      thread.join(MAX_WAIT_TIME);  
  7.      if (thread.isSuccess()) {  
  8.           result_lst = thread.getResults();  
  9.      } else {  
  10.           throw new DataBaseTimeoutException();  
  11.      }  
  12. catch (Exception e) {  
  13.      thread.interrupt();  
  14.      ........  
  15. }  
  16. MAX_WAIT_TIME就是最大等待时间20秒,如果join()到达最长等待时间,但 是SearchThread里面的success_flag还没有被设置成true的时候,就是说明已经超时,检索没有完成,这个时候会抛出自定义的 DataBaseTimeoutException,中断线程。
Java线程池中,设置核心线程超时时间涉及两个关键参数:`keepAliveTime` 和 `allowCoreThreadTimeOut`。通过这两个参数的配合使用,可以控制核心线程是否以及何时被回收。 ### 设置核心线程超时时间 #### 1. 启用核心线程超时机制 默认情况下,线程池的核心线程不会因为空闲而被回收,即使设置了 `keepAliveTime`。要使核心线程也受超时机制的影响,需要将 `allowCoreThreadTimeOut` 参数设置为 `true`。该操作可以通过调用 `ThreadPoolExecutor` 提供的 `setAllowCoreThreadTimeOut(boolean)` 方法实现[^2]。 示例代码: ```java ThreadPoolExecutor executor = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue ); // 允许核心线程超时回收 executor.setAllowCoreThreadTimeOut(true); ``` #### 2. 设置超时时间(`keepAliveTime`) `keepAliveTime` 表示线程池中空闲线程的存活时间。当某个线程空闲超过这个时间后,如果线程池当前线程数大于核心线程数(core pool size),或者启用了 `allowCoreThreadTimeOut` 并且线程是空闲的,则该线程会被终止并从线程池中移除。 示例代码: ```java ThreadPoolExecutor executor = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, 60, // 核心线程和非核心线程超时时间为60秒 TimeUnit.SECONDS, workQueue ); // 允许核心线程超时回收 executor.setAllowCoreThreadTimeOut(true); ``` #### 3. 配置线程池的完整示例 以下是一个完整的线程池配置示例,包括启用核心线程超时机制和设置超时时间: ```java import java.util.concurrent.*; public class ThreadPoolExample { public static void main(String[] args) { int corePoolSize = 5; int maximumPoolSize = 10; long keepAliveTime = 60; BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(); ThreadPoolExecutor executor = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue ); // 允许核心线程超时回收 executor.setAllowCoreThreadTimeOut(true); // 提交任务 for (int i = 0; i < 10; i++) { final int taskNumber = i; executor.execute(() -> { System.out.println("Executing task " + taskNumber); try { Thread.sleep(2000); // 模拟任务执行时间 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } // 关闭线程池 executor.shutdown(); } } ``` ### 注意事项 - **性能优化**:在高并发场景下,合理设置核心线程超时时间可以避免线程池长时间持有大量空闲线程,从而降低服务器资源消耗,防止 CPU 使用率持续飙升[^3]。 - **适用场景**:通常建议在负载波动较大的系统中启用 `allowCoreThreadTimeOut`,以便动态调整线程数量,提升资源利用率。 - **兼容性**:确保使用的线程池队列类型(如 `LinkedBlockingQueue` 或 `SynchronousQueue`)与 `allowCoreThreadTimeOut` 的行为相匹配,以避免意外的行为。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值