6 回答

TA贡献1825条经验 获得超6个赞
今天刚刚看过并发编程实战关于可变对象的安全发布与访问:
安全发布:
在静态初始化函数中初始化一个对象引用;
将对象的引用保存在volatile或AtomicReference上
将对象的引用保存到某个正确构造对象的final类型上
将对象保存在一个锁的范围内.
安全访问:
线程封闭
只读共享
线程安全共享, 该发布对象内部的访问方式是线程安全的, 就不需要外部同步了
保护对象, 发布可变对象的对象通过限制外界的访问, 指定访问可变对象的接口.
static List<String> arrayList = new ArrayList<>();
这样已经符合了安全发布的第一条
那么就要保证安全访问了, 由于list肯定不能安全访问的前三种情况, 那么只能依靠在发布对象时,限制外界的访问, 也就是加锁.

TA贡献2041条经验 获得超4个赞
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(10);
List<Callable<Integer>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(newTask(i));
}
try {
for (Future<Integer> future : exec.invokeAll(list)) {
try {
System.out.println(future.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
exec.shutdown();
}
static Callable<Integer> newTask(final int t) {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("newTask: " + t);
try {
Thread.sleep((10 - t) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return t;
}
}
}
添加回答
举报