juc包下的常见类
Semaphore
一个计数信号量,主要用于控制多线程对共同资源库访问的限制
停车场实例
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadDemo98 {
public static void main(String[] args) {
//创建信号量
Semaphore semaphore = new Semaphore(2);
ThreadPoolExecutor executor = new ThreadPoolExecutor(10,10,0,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(100));
for (int i = 0; i <4 ; i++) {
//创建线程1
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"到达停车场");
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
//试图进入停车场
try {
semaphore.acquire();
}catch (InterruptedException e){
e.printStackTrace();
}//
//
System.out.println(Thread.currentThread().getName()+"进入停车场");
//
int num = 1+new Random().nextInt(5);
try {
Thread.sleep(num*1000);
}catch (InterruptedException e){
e.printStackTrace();
}
//离开停车厂
System.out.println(Thread.currentThread().getName()+"离开停车场");
//释放锁
semaphore.release();
}
});
}
}
}
//结果:
pool-1-thread-2到达停车场
pool-1-thread-4到达停车场
pool-1-thread-3到达停车场
pool-1-thread-1到达停车场
pool-1-thread-4进入停车场
pool-1-thread-3进入停车场
pool-1-thread-3离开停车场
pool-1-thread-2进入停车场
pool-1-thread-4离开停车场
pool-1-thread-1进入停车场
pool-1-thread-2离开停车场
pool-1-thread-1离开停车场
CountDownLatch
CountDownLatch是如何实现的?
在CountDownLatch内有一计数器,每次调用CountDown方法时计数器的数量减一,到达零值时,就可以执行await方法
比赛实例
在这里插入代码片
CountDownLatch缺点
CountDownLatch计时器的使用是一次性的,使用完后
CyclicBarrier改进:
CyclicBarrier cyclicBarrier = new CyclicBarrier(new Runnable(){
@Override
public void run{
System.out.println("执行");
}
});
cyclicBarrier.await();
CyclicBarrier和CountDownLatch区别
CountDownLatch计数器只能使用一次,CyclicBarrier计数器可以重复使用
HashMap
缺点:
ConcurrentHashMap
JDK1.8优化,读的时候不加锁,写的时候枷锁加锁,使用了大量的CAS\VOILTAIL
HashTable
线程安全的容器,给put方法加锁,一般不使用
HashMap、HashTable、ConcurrentHashMap区别?
- HashMap是非线程安全的容器,在JDK1.7会造成死循环,JDK1.8会造成数据覆盖;HashTable、ConcurrentHashMap都是线程安全的。
- HashTable实现线程的手段比较简单,在put方法整体加了一把锁,使用synchronized修饰,因此性能不高,所以使用频率较低
Java中线程安全的数据结构
1.HashTable:线程安全类,通过对其方法函数进行synchroized修饰其特性,效率低下
2.ConcurrentHashMap:不仅可以在需要保证数据安全的场景中替换HashMap,也有不错的性能
3.CopyOnWriteArrayList:是线程安全的List接口实现,在高并发的情况下可以提供高性能的并发读取,并且保证读的内容一定是正确的。
4.CopyOnWriteArraySet理解为线程安全的Set
5.Vector,利用synchronized同步锁机制实现线程安全,实现方式类似HashTable。
6.StringBuffer:线程安全。