[英]Java FixedThreadPool with resources per thread?
這是我當前工作代碼的偽代碼版本:
public class DataTransformer {
private final boolean async = true;
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
public void modifyAsync(Data data) {
if (async) {
executorService.submit(new Runnable() {
@Override
public void run() {
modify(data);
}
});
} else {
modify(data);
}
}
// This should actually be a variable inside modify(byte[] data)
// But I reuse it to avoid reallocation
// This is no problem in this case
// Because whether or not async is true, only one thread is used
private final byte[] temp = new byte[1024];
private void modify(Data data) {
// Do work using temp
data.setReady(true); // Sets a volatile flag
}
}
請閱讀評論。 但現在我想使用Executors.newFixedThreadPool(10)
而不是Executors.newSingleThreadExecutor()
。 在我的情況下,這很容易通過在modify(Data data)
中移動字段temp
來實現,這樣每次執行都有自己的temp
數組。 但這不是我想做的,因為我想盡可能重用數組。 相反,我希望 10 個線程中的每一個都有一個temp
數組。 實現這一目標的最佳方法是什么?
由於static
變量在所有線程之間共享,因此您可以聲明為 static。 但是如果你想使用不同的值,那么要么使用 Threadlocal,要么使用不同的 object。
使用 ThreadLocal 你可以:
ThreadLocal<byte[]> value = ThreadLocal.withInitial(() -> new byte[1024]);
您也可以像這樣使用 object:
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
class Control {
public volatile byte[] temp = "Hello World".getBytes();
}
final Control control = new Control();
class T1 implements Runnable {
@Override
public void run() {
String a = Arrays.toString(control.temp);
System.out.println(a);
}
}
class T2 implements Runnable {
@Override
public void run() {
String a = Arrays.toString(control.temp);
System.out.println(a);
}
}
private void test() {
T1 t1 = new T1();
T2 t2 = new T2();
new Thread(t1).start();
new Thread(t2).start();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.