Java之线程池管理

JDK5后建议使用ExecutorService与Excutors来创建与管理线程池, 不再建议直接使用Thread. 开始不明白原因, 今天知道结果了:
使用Thread.currnetThread.join()后,线程卡着无法退出, 事实二个子线程已经完成了. 使用这个方法是等待子线程完成后再自行退出. 结果卡壳了.
final FileCache cache = new FileCache(LoganalyseConfig.getInstance()).open();
  try {

   new Thread() {
    public void run() {
     try {
      testPut(cache);
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }.start();

   new Thread() {
    public void run() {
     try {
      testGet(cache);
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }.start();

   Thread.currentThread().join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  } finally {
   if (cache != null) {
    cache.close();
   }
  }
==========================================================
executor.submit(new Runnable() {
    public void run() {
     try {
      testPut(cache);
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   });

   executor.submit(new Runnable() {
    public void run() {
     try {
      testGet(cache);
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   });
   executor.shutdown();
   executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
   System.out.println("退出testPutGet()");

posted @ 2016-09-07 14:17  zolo®  阅读(163)  评论(0编辑  收藏  举报