java如何向synchronizedList添加线程安全方法
public class ListHelper {
private final List<String> list= Collections.synchronizedList(new ArrayList<>());
public boolean putIfAbsent(String x) {
System.out.println(Thread.currentThread().getName()+" start putIfAbsent");
synchronized (list){
boolean absent=!list.contains(x);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (absent){
System.out.println("add前hashcode: "+list.hashCode());
list.add(x);
}
System.out.println(Thread.currentThread().getName()+" end putIfAbsent");
return absent;
}
}
public static void main(String[] args) throws InterruptedException {
ListHelper helper = new ListHelper();
CountDownLatch countDownLatch = new CountDownLatch(2);
String a = "a";
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"-"+helper.putIfAbsent(a));
countDownLatch.countDown();
},"A").start();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"-list.add() start");
System.out.println(Thread.currentThread().getName()+"-"+helper.list.add(a));
countDownLatch.countDown();
},"B").start();
countDownLatch.await();
for (Object o : helper.list) {
System.out.println(o);
}
}
}
我认为使用list
作为锁是正确的,但程序的输出让我惊讶。
程序输出如下所示:
A start putIfAbsent
B-list.add() start
A end putIfAbsent
A-true
B-true
a
a
list
似乎并不相互排斥
共 (0) 个答案