我是靠谱客的博主 舒服草莓,这篇文章主要介绍线程安全的类,Lock锁,现在分享给大家,希望可以做个参考。

线程安全
-------->
线程不安全
StringBuffer
StringBuilder
Vactor
ArrayList
Hashtable
HashMap

不过一般多线程环境下,也不使用 Vector 和 Hashtable

// 通过使用 Collections 集合工具类, 转为线程安全
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();	// Lock 仅是 接口, 这里用实现类创建
@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();
// 解锁
}
}
}
}

最后

以上就是舒服草莓最近收集整理的关于线程安全的类,Lock锁的全部内容,更多相关线程安全内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(139)

评论列表共有 0 条评论

立即
投稿
返回
顶部