java.util.concurrent
锁:
synchronized:关键词、粒度大、可重入、非公平
Lock:类、细粒度、可重入、可公平可非公平
使用lock时注意解锁
以List集合为例子
如下代码,多个线程操作同一个资源,会出现并发修改异常
//多线程下操作同一个资源,未加锁情况下
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100; i++) {
final String temp = i+"";
new Thread(() -> {
list.add(temp+"");
},temp).start();
}
}
System.out.println(list);
}
普通的vector还有collections都是依靠synchronized修饰
//Vector的add方法由synchronized修饰
public static void main(String[] args) {
Vector<String> list = new Vector();
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100; i++) {
final String temp = i+"";
new Thread(() -> {
list.add(temp+"");
},temp).start();
}
}
System.out.println(list);
}
//Collections.synchronizedList();方法add也是由synchronized修饰
public static void main(String[] args) {
List<String> list = Collections.synchronizedList(new ArrayList<String>());
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100; i++) {
final String temp = i+"";
new Thread(() -> {
list.add(temp+"");
},temp).start();
}
}
System.out.println(list);
}
并发包下的list是由lock锁修饰
//CopyonWriteArrayList的add方法由lock锁,需要手动解锁unlock
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100; i++) {
final String temp = i+"";
new Thread(() -> {
list.add(temp+"");
},temp).start();
}
}
System.out.println(list);
}