简体   繁体   English

如何在ThreadFactory中初始化ThreadLocal变量?

[英]How to init ThreadLocal variable in ThreadFactory?

I have n resources and n threads, each thread will use a resource for its tasks. 我有n个资源和n个线程,每个线程将使用一个资源来执行其任务。
When thread is created I want it to receive a resources and store it local thread variable. 创建线程时,我希望它接收资源并将其存储在本地线程变量中。
When thread is done, I need to release the resource 线程完成后,我需要释放资源

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;
        }
});

Rewrite getResource() and releaseResource() according to your needs. 根据需要重写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());
            }
        }
    };
  }
}

Test code: 测试代码:

    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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM