java.util.concurrent包
java.util.concurrent包
1. 线程计数
有时候我们需要对线程间做计数,或者是统计.这时候我们需要这些类
public class Test {
public static void invoke(){
// 可以理解为停车位 , 有三个停车位,十个线程是车
// 只有车离开才会进下一辆车
Semaphore available = new Semaphore(3, true);
try {
// 获取许可进入
available.acquire();
System.out.println(Thread.currentThread().getName()+" : 进入invoke()");
Thread.sleep(3000);
// 释放许可
available.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
// countDownLatchDemo();
// cyclicBarrierDemo();
for (int i = 1; i <= 10; i++) {
new Thread(() -> {
invoke();
},"test"+i).start();
}
}
private static void cyclicBarrierDemo() {
// 线程屏障,如果没有满足条件 ,线程会一直在await()阻塞
CyclicBarrier cyclicBarrier = new CyclicBarrier(50);
Map<String,String> map = new ConcurrentHashMap<>();
for (int i = 1; i <= 50; i++) {
int a = i;
System.out.println("a : "+a);
new Thread(() -> {
UUID uuid = UUID.randomUUID();
map.put(a+"",uuid.toString());
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
map.entrySet().forEach(System.out::println);
},"test"+i).start();
}
}
private static void countDownLatchDemo() throws InterruptedException {
// 计数器
// 设置50个累计数
// 每调用一次countDownLatch.countDown()就会累计+1
// countDownLatch.await() : 如果计数未到指定值,它会阻塞
CountDownLatch countDownLatch = new CountDownLatch(50);
Map<String,String> map = new ConcurrentHashMap<>();
for (int i = 1; i <= 50; i++) {
int a = i;
new Thread(() -> {
UUID uuid = UUID.randomUUID();
map.put(a+"",uuid.toString());
countDownLatch.countDown();
},"test"+i).start();
}
countDownLatch.await();
map.entrySet().forEach(System.out::println);
}
}
2. 集合安全
平时使用的集合大部分都是不安全的,当我们需要线程安全的集合时,java已经为我们提供好了!
/**
* 安全集合框架
*
* @Author: blaaair
**/
public class Test {
public static void main(String[] args) {
//safeListDemo();
// safeMap();
}
private static void safeMap() {
Map<String,String> map = new ConcurrentHashMap<>();
for (int i = 1; i <= 50 ; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString());
System.out.println(map);
},i+"").start();
}
}
private static void safeListDemo() {
// 不安全List
// List<String> list = new ArrayList<>();
// 安全List
// list set 同理,CopyOnWriteArraySet<>();
List<String> list =new CopyOnWriteArrayList<>();
for (int i = 1; i <= 50 ; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString());
list.forEach(System.out::println);
},i+"").start();
}
}
}
java.util.concurrent包
https://www.blaaair.com/archives/javautilconcurrent-bao