这是我目前工作代码的一个伪代码版本。
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()
. 在我的例子中,通过移动领域,这很容易实现。temp
里面 modify(Data data)
,使每次执行都有自己的 temp
数组。但这不是我想做的,因为我想尽可能的重复使用这个数组。相反,我想为10个线程中的每一个线程建立一个 temp
阵列。有什么最好的方法来实现这个目标?
作为 static
变量是所有线程共享的,所以你可以声明为静态变量。但如果你想使用不同的值,那么要么使用Threadlocal,要么使用不同的对象。
使用ThreadLocal,你可以用.NET对象。
ThreadLocal<byte[]> value = ThreadLocal.withInitial(() -> new byte[1024]);
你也可以使用这样的对象。
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();
}
}