阿神2017-04-18 10:10:52
I just watched the practical concurrent programming today about the safe release and access of mutable objects:
Secure release:
Initialize an object reference in a static initialization function;
Save the reference of the object on volatile or AtomicReference
Save the reference of the object to a final type that correctly constructs the object
Save objects within the scope of a lock.
Secure Access:
Thread closed
Read-only sharing
Thread-safe sharing, the internal access method of the published object is thread-safe, and no external synchronization is required
Protect objects, publish mutable objects by restricting external access, and specify the interface for accessing mutable objects.
static List<String> arrayList = new ArrayList<>();
This has complied with the first rule of safe publishing
Then we must ensure safe access. Since the list must not be safely accessed in the first three situations, we can only rely on restricting external access when publishing objects, that is, adding Lock.
PHP中文网2017-04-18 10:10:52
It can be realized according to the request of the subject, but the realization of this demand is very strange.
private static void test1(final int i) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (arrayList) {
while (arrayList.size() != i) {
try {
arrayList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
arrayList.add(i, i + "position");
arrayList.notifyAll();
}
}
}).start();
}
In addition to this method, it can also be achieved through join
和传入countdownlatch
. If you really want to be like the subject, it is better not to use multi-threading
天蓬老师2017-04-18 10:10:52
Use the invokeAll method of the thread pool to ensure that the order of the results is consistent with the order of the parameters passed in
黄舟2017-04-18 10:10:52
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;
}
}
}