package com.bj.thread;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
/**
* @FileName: TestLock
* @Remark:
* @Author lirongbin
* @Date 2022-03-20
* @Version 1.0.0
*/
public class TestLock {
public static void main(String[] args) {
Locker locker=new Locker();
// 第二种:三个线程操作同一个对象
// new Thread(locker).start();
// new Thread(locker).start();
// new Thread(locker).start();
// 第一种 ,用线程池可以保证线程安全
// ExecutorService executorService = Executors.newFixedThreadPool(10);
// executorService.execute(locker);
// executorService.shutdown();
// CopyOnWriteArrayList list=new CopyOnWriteArrayList();
// List list=new ArrayList();
// Map map=new HashMap();
Map map=new ConcurrentHashMap();
for (int i = 0; i < 30000; i++) {
int finalI = i;
new Thread(()->{
map.put(finalI +"",Thread.currentThread().getName());
// list.add(Thread.currentThread().getName());
// System.out.println(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("集合大小为:"+map.size());
}
}
class Locker implements Runnable {
int ticketNums = 10;
// 定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
// 枷锁
lock.lock();
try {
// 业务代码
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else {
break;
}
} finally {
lock.unlock();
}
}
}
}
线程安全的集合 CopyOnWriteArrayList,ConcurrentHashMap
最新推荐文章于 2025-04-23 17:10:32 发布