1. 一个简单的例子
public class MultiThread {
public static final List<Long> list = Collections.synchronizedList(new ArrayList<Long>());
public static void main(String[] args) {
for(int i = 1;i<=100;i++){
list.add(Long.valueOf(i));
}
MyThread myThread = new MultiThread().new MyThread();
Thread t1 = new Thread(myThread);
t1.setName("线程1");
t1.start();
Thread t2 = new Thread(myThread);
t2.setName("线程2");
t2.start();
Thread t3 = new Thread(myThread);
t3.setName("线程3");
t3.start();
}
public class MyThread implements Runnable{
@Override
public void run() {
for(int i = 0;i<list.size();i++){
// 同步list,打印数据并删除该数据
synchronized (list) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.out.print(Thread.currentThread().getName() + ":" + list.get(i)+"\n");
list.remove(i);
}
}
}
}
}
2. Collections.synchronizedList保证了, ArrayLIst的add. get等操作时, 有锁.
但是这种情况下, 不能保证线程同步.
if(!list.size() > 0) {
list.remove(0);
}
isEmpty之后, 其他线程进行了list数据操作, 那么此时的get对应的list已经改变. 那么就需要使用synchronized
synchronized(list) { if(!list.isEmpty()) {
} }list.remove(0);
实际上使用sybchronized是为了此此操作的原子性.