java.util.concurrent,并發(fā)包
- CopyOnWriteArrayList是線程安全的。
package util;
import java.util.concurrent.CopyOnWriteArrayList;
public class TestCopyOnWriteArrayList {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for(int i = 0; i< 10000;i++){
new Thread(()->{
list.add(Thread.currentThread().getName());
});
}
try {
Thread.sleep(3000);//這里是為了防止主線程先執(zhí)行完,而子線程還沒(méi)有創(chuàng)建完,獲取的list.size()可能不準(zhǔn),所以讓主線程休眠,確保子線程執(zhí)行完。
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
- java.util.concurrent.locks.Lock
synchronized是隱式鎖,Lock是顯示鎖。ReentrantLock類是可重入鎖,實(shí)現(xiàn)了Lock,不要忘記釋放鎖。

image

image
import java.util.concurrent.locks.ReentrantLock;
public class TestLock implements Runnable {
private static int ticketNum = 3;
private boolean flag = true;
//定義Lock鎖
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (flag) {
try {
lock.lock();//加鎖
if (ticketNum > 0) {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "獲得票" + ticketNum--);
} else {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock(); //釋放鎖
}
}
}
public static void main(String[] args) {
TestLock lock = new TestLock();
Thread thread = new Thread(lock);
Thread thread1 = new Thread(lock);
Thread thread2 = new Thread(lock);
thread.start();
thread1.start();
thread2.start();
}
}