【发布时间】:2014-05-09 05:58:28
【问题描述】:
注意:我是英文新手,如有错误请见谅。
我使用线程本地来保存每个线程的资源;并在某些任务中使用它(线程本地)。我通过 java executor-service 运行我的任务。当线程要终止时,我会关闭我的资源;然后我需要在我调用“executor.shoutdown”方法之后,通过 executor-service 在所有创建的线程中运行一个任务。我如何强制执行程序在每个线程中运行一个任务,什么时候会终止这些任务?
import java.util.concurrent.*;
public class Main2 {
public static void main(String[] args) {
ExecutorService executor = new ForkJoinPool(3);
SimpleValue val = new SimpleValue();
for(int i=0; i<1000; i++){
executor.execute(new Task(val));
}
executor.shutdown();
while( true ) {
try {
if( executor.awaitTermination(1, TimeUnit.SECONDS) ) System.exit(0);
} catch(InterruptedException intrExc) {
// continue...
}
}
}
protected static interface ResourceProvider<T>
extends AutoCloseable {
public T get();
public ResourceProvider<T> reset() throws Exception;
public ResourceProvider<T> reset(boolean force) throws Exception;
public void close();
}
protected static abstract class ThreadLocalResourceProvider<T>
extends ThreadLocal<T>
implements ResourceProvider<T> {}
protected static class SimpleValue
extends ThreadLocalResourceProvider<String> {
public String initialValue() {
return "Hello " + Thread.currentThread().getName();
}
public SimpleValue reset() throws Exception {
return reset(false);
}
public SimpleValue reset(boolean force) throws Exception{
set(this.initialValue());
return this;
}
public void close() {
remove();
}
}
protected static class Task
implements Runnable {
protected SimpleValue val;
public Task(SimpleValue val) {
this.val = val;
}
@Override
public void run() {
try {
System.out.print(val.reset().get());
} catch( Exception exc ) {
System.out.print( exc.getMessage() );
}
}
}
}
【问题讨论】:
标签: java multithreading executorservice thread-local