2014-03-26 17 views
0

我有n个资源和n个线程,每个线程都会为其任务使用资源。
创建线程时,我希望它接收资源并将其存储在本地线程变量中。
当线程完成,我需要释放资源如何在ThreadFactory中初始化ThreadLocal变量?

ExecutorService pool = Executors.newFixedThreadPool(10, new ThreadFactory() { 
     public Thread newThread(final Runnable r) { 
      Thread thread = new Thread(new Runnable() { 
       public void run() { 
         //set ThreadLocal with a resource 
         //run 
         //close the resource 
       } 
      }); 
       return thread; 
     } 
}); 
+0

扩展Thread并通过你需要构造函数的值 – Bob

回答

1

重写getResource()方法,并根据您的需要releaseResource()。

class MyThreadFactory implements ThreadFactory { 
     // String is the type of resource; change it if nesessary 
    static final ThreadLocal<String> currentResourceKey = new ThreadLocal<String>(); 

    int n = 0; 

    String getResource() { 
    n++; 
    System.out.println("aquired:" + n); 
    return Integer.valueOf(n).toString(); 
    } 

    void releaseResource(String res) { 
    System.out.println("released:" + res); 
    } 

    @Override 
    public Thread newThread(Runnable r) { 
    return new Thread(r) { 
     public void run() { 
      currentResourceKey.set(getResource()); 
      try { 
       super.run(); 
      } finally { 
       releaseResource(currentResourceKey.get()); 
      } 
     } 
    }; 
    } 
} 

测试代码:

ExecutorService pool = Executors.newFixedThreadPool(2,new MyThreadFactory()); 
    for (int k = 0; k < 5; k++) { 
     pool.submit(new Runnable() { 
      public void run() { 
       String res = currentResourceKey.get(); 
       try { 
        Thread.sleep(50); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       System.out.println(" executed:"+res+" on "+Thread.currentThread().getName()); 
      } 
     }); 
    } 
    pool.shutdown();