静态变量是全局的
vector的add方法加了同步函数,加了synchronize关键字
synchronizedMap
Collections.synchronized*(m) 将线程不安全额集合变为线程安全集合
HashMap map=new HashMap();
map.put("","");
Collections.synchronizedMap(map);
HashTable jdk1.5
ConcurrentHashMap
并发集合 效率高,线程安全,减少锁的资源竞争
ConcurrentMap接口下有俩个重要的实现 :
ConcurrentHashMap
ConcurrentskipListMap (支持并发排序功能。弥补ConcurrentHas hMa p)
ConcurrentHashMap内部使用段(Segment)来表示这些不同的部分,每个段其实就是一个小的HashTable,它们有自己的锁。只要多个修改操作发生在不同的段上,它们就可以并发进行。把一个整体分成了16个段(Segment.也就是最高支持16个线程的并发修改操作。这也是在重线程场景时减小锁的粒度从而降低锁竞争的一种方案。并且代码中大多共享变使用volatile关键字声明,目的是第一时间获取修改的内容,性能非常好。
CountDownLatch 计数器
CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了
CyclicBarrier
CyclicBarrier初始化时规定一个数目,然后计算调用了CyclicBarrier.await()进入等待的线程数。当线程数达到了这个数目时,所有进入等待状态的线程被唤醒并继续。
CyclicBarrier就象它名字的意思一样,可看成是个障碍, 所有的线程必须到齐后才能一起通过这个障碍。
CyclicBarrier初始时还可带一个Runnable的参数, 此Runnable任务在CyclicBarrier的数目达到后,所有其它线程被唤醒前被执行。
Semaphore(重要)
//最多支持多个资源访问
Semaphore semaphore=new Semaphore(5);
semaphore.acquire();//获取资源权限
semaphore.availablePermits();//获取资源后减一
semaphore.release();//释放资源
也可以创建计数为1的Semaphore,将其作为一种类似互斥锁的机制,这也叫二元信号量,表示两种互斥状态。它的用法如下:
availablePermits函数用来获取当前可用的资源数量
wc.acquire(); //申请资源
wc.release();// 释放资源
需求: 一个厕所只有3个坑位,但是有10个人来上厕所,那怎么办?假设10的人的编号分别为1-10,并且1号先到厕所,10号最后到厕所。那么1-3号来的时候必然有可用坑位,顺利如厕,4号来的时候需要看看前面3人是否有人出来了,如果有人出来,进去,否则等待。同样的道理,4-10号也需要等待正在上厕所的人出来后才能进去,并且谁先进去这得看等待的人是否有素质,是否能遵守先来先上的规则。
代码:
测试
并发队列
在并发队列上JDK提供了两套实现,一个是以ConcurrentLinkedQueue为代表的高性能队列,一个是以BlockingQueue接口为代表的阻塞队列,无论哪种都继承自Queue。
ConcurrentLinkedDeque
适用于高并发场景下的队列,通过无锁的方式,实现了高并发状态下的高性能,通常ConcurrentLinkedQueue性能好于BlockingQueue.它是一个基于链接节点的无界线程安全队列。该队列的元素遵循先进先出的原则。头是最先
加入的,尾是最近加入的,该队列不允许null元素。
ConcurrentLinkedQueue重要方法:
add 和offer() 都是加入元素的方法(在ConcurrentLinkedQueue中这俩个方法没有任何区别)
poll() 和peek() 都是取头元素节点,区别在于前者会删除元素,后者不会
使用BlockingQueue模拟生产者与消费者--阻塞队列
package thread;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class ProducerThread implements Runnable {
private BlockingQueue queue;
private volatile boolean flag = true;
private static AtomicInteger count = new AtomicInteger();
public ProducerThread(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
System.out.println("生产线程启动...");
while (flag) {
System.out.println("正在生产数据....");
String data = count.incrementAndGet()+"";
// 将数据存入队列中
boolean offer = queue.offer(data, 2, TimeUnit.SECONDS);
if (offer) {
System.out.println("生产者,存入" + data + "到队列中,成功.");
} else {
System.out.println("生产者,存入" + data + "到队列中,失败.");
}
Thread.sleep(1000);
}
} catch (Exception e) {
} finally {
System.out.println("生产者退出线程");
}
}
public void stop() {
this.flag = false;
}
}
class ConsumerThread implements Runnable {
private BlockingQueue<String> queue;
private volatile boolean flag = true;
public ConsumerThread(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
System.out.println("消费线程启动...");
try {
while (flag) {
System.out.println("消费者,正在从队列中获取数据..");
String data = queue.poll(2, TimeUnit.SECONDS);
if (data != null) {
System.out.println("消费者,拿到队列中的数据data:" + data);
Thread.sleep(1000);
} else {
System.out.println("消费者,超过2秒未获取到数据..");
flag = false;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("消费者退出线程...");
}
}
}
public class Test006 {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
ProducerThread producerThread1 = new ProducerThread(queue);
ProducerThread producerThread2 = new ProducerThread(queue);
ConsumerThread consumerThread1 = new ConsumerThread(queue);
Thread t1 = new Thread(producerThread1);
Thread t2 = new Thread(producerThread2);
Thread c1 = new Thread(consumerThread1);
t1.start();
t2.start();
c1.start();
// 执行10s
Thread.sleep(10 * 1000);
producerThread1.stop();
producerThread2.stop();
}
}