线程安全 --------> 线程不安全
StringBuffer StringBuilder
Vactor ArrayList
Hashtable HashMap
不过一般多线程环境下,也不使用 Vector 和 Hashtable
List<String> list = Collections.synchronizedList(new ArrayList<String>());
Map<String,String> map = Collections.synchronizedMap(new HashMap<String,String>());
Lock锁
Lock实现比使用 synchronized 获得更广泛的锁定操作,和 synchronized 作用一样
public class SellTicket implements Runnable{
private int tickets = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try{
lock.lock();
if(tickets > 0){
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}finally {
lock.unlock();
}
}
}
}
|