java多线程(十四)八锁CopyOnWriteArrayListCopyOnWriteArraySetConcurrentHashMapCallable
Posted 500年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程(十四)八锁CopyOnWriteArrayListCopyOnWriteArraySetConcurrentHashMapCallable相关的知识,希望对你有一定的参考价值。
1、八锁
1、同一把锁时,谁先拿到,谁执行;
2、new this 锁为具体的对象;
3、static 锁为Class唯一的一个模板;
2、CopyOnWriteArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListDemo {
public static void main(String[] args) {
// List<String> list = new ArrayList<String>();// 线程不安全
// List<String> list = new Vector<>();
// List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
list.add(Thread.currentThread().getName());
System.out.println(list);
}, String.valueOf(i)).start();
}
}
}
3、CopyOnWriteArraySet
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public class CopyOnWriteArraySetDemo {
public static void main(String[] args) {
// Set<String> set = new HashSet<String>();// 不安全
// Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet<String>();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
set.add(Thread.currentThread().getName());
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
4、ConcurrentHashMap
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapDemo {
public static void main(String[] args) {
// Map<String, String> map = new HashMap<String, String>();// 多线程-不安全
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), Thread.currentThread().getName());
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}
5、Callable
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
new Thread(futureTask).start();
new Thread(futureTask).start();
String string = futureTask.get();// 此处可能会产生阻塞
System.out.println(string);
}
}
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("call");
return "hao";
}
}
特别鸣谢:狂神说Java老师的无私奉献
.
.
.
上一篇 java多线程(十三)Condition精准通知唤醒
以上是关于java多线程(十四)八锁CopyOnWriteArrayListCopyOnWriteArraySetConcurrentHashMapCallable的主要内容,如果未能解决你的问题,请参考以下文章