您的位置:首页 > 其它

线程间通信/同步类容器和并发类容器

2017-04-05 20:55 134 查看

线程之间通信

线程通信的概念:线程是操作系统中独立的个体,但这些个体如果不经过特殊的处理就不能成为一个整体,线程之间的通信就成为整体的必要方式之一。当线程存在通信指挥。系统间的交互性就会更强大,在提高CPU利用率的同时还会使开发人员对线程任务在处理的过程中进行邮箱的把控和监督。

使用if/else

public class ListAdd1 {

private volatile static List list = new ArrayList();

public void add(){
list.add("bjsxt");
}

public int size(){
return list.size();
}

public static void main(String[] args) {
final ListAdd1 list1 = new ListAdd1();
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
for(int i=0;i<10;i++){
list1.add();
System.out.println("当期线程:"+Thread.currentThread().getName()+"添加了一个元素。。");
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1");

Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
while(true){
if(list1.size()==5){
System.out.println("当前线程接收到通知:"+Thread.currentThread().getName()+" list.size = 5 线程停止");
throw new RuntimeException();
}
}
}
},"t2");

t1.start();
//当list中的元素大小等于5,停止t2线程
t2.start();

}
}


使用wait/notify方法实现线程间的通信。(主要这两个方法都是Object的类的方法,换句话说java为所有对象提供了这两个方法)

1.wait和notify必须配合synchronized关键字使用

2.wait方法释放锁,notify方法不释放锁。

使用wait/notify模拟Queue

BlockingQueue:顾名思义,首先它是一个队列,并且支持阻塞的机制,阻塞的放入和得到数据。我们要实现LinkedBlockingQueue下面两个简单的方法put和take

put(anObject)把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断,知道BlockingQueue里面有空间再继续。

take:取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻塞进入等待状态直到BlockingQueue有新的数据被加入。

public class ListAdd2 {

private volatile static List list = new ArrayList();

public void add(){
list.add("bjsxt");
}

public int size(){
return list.size();
}

public static void main(String[] args) {

final ListAdd2 list2 = new ListAdd2();

//实例化出来一个lock
//当使用wait和notify的时候,一定要配合synchronized关键字去使用
//创建一个对象,用这个对象当成一把锁
final Object lock = new Object();

Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
synchronized (lock) {
for(int i=0;i<10;i++){
list2.add();
System.out.println("当前线程:"+Thread.currentThread().getName()+" 添加了一个元素");
Thread.sleep(500);
if(list.size()==5){
System.out.println("已经发出通知");
lock.notify();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1");

Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
//wait 和 notify方法必须与synchronized方法配合使用
synchronized (lock) {
if(list.size()!=5){
try {
//wait方法释放锁 notify方法不释放锁
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//size等于5的情况
System.out.println("当前线程:"+Thread.currentThread().getName()+"收到通知线程停止...");
throw new RuntimeException();
}
}
},"t2");
t2.start();
t1.start();
}
}


CountDownLatch实现实时通知,无需使用synchronized

public class ListAdd3 {

private volatile static List list = new ArrayList();

public void add(){
list.add("bjsxt");
}

public int size(){
return list.size();
}

//实现实时的通知效果
static final CountDownLatch countDownLatch = new CountDownLatch(2);

public static void main(String[] args) {

final ListAdd3 list2 = new ListAdd3();

Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
for(int i=0;i<10;i++){
list2.add();
System.out.println("当前线程:"+Thread.currentThread().getName()+" 添加了一个元素");
Thread.sleep(500);
if(list.size()==5){
System.out.println("已经发出通知");
countDownLatch.countDown();
countDownLatch.countDown();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1");

Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
//wait 和 notify方法必须与synchronized方法配合使用
if(list.size()!=5){
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//size等于5的情况
System.out.println("当前线程:"+Thread.currentThread().getName()+"收到通知,线程停止...");
throw new RuntimeException();
}
},"t2");
t1.start();
t2.start();
}
}


ThreadLocal

ThreadLocal概念:线程局部变量,是一种多线程间并发访问变量的解决方案。其与synchronized等加锁的方式不同,ThreadLocal完全不提供锁,而使用以空间换时间的手段,为每个线程提供变量的独立副本,以保障线程安全。

从性能上说,ThreadLocal不具有绝对的优势,在并发不是很高的时候,加锁的性能会更好,但作为一套与锁完全无关的线程安全解决方案,在高并发或竞争激烈的场景,使用ThreadLocal可以在一定程度上减少锁减少锁竞争。

public class ConnThreadLocal {

public static ThreadLocal<String> th = new ThreadLocal<String>();

public void setTh(String value){
th.set(value);
}

public void getTh(){
System.out.println(Thread.currentThread().getName()+":"+this.th.get());
}

public static void main(String[] args) {
final ConnThreadLocal ct = new ConnThreadLocal();

Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
ct.setTh("张三");
ct.getTh();
}
},"t1");

Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(1000);
ct.getTh();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t2");
t1.start();
t2.start();
}
}


单例和多线程

单例模式,最常见的是饥饿模式和懒汉模式。一个直接实例化对象,一个在调用方法是实例化对象。在多线程模式中,考虑到性能和线程安全问题,我一般选择下面两种经典的单例模型,在性能提升的同时,又保证了线程安全。

- dubble checkout instance

public class DubbleSingleton {

private static DubbleSingleton ds;

public static DubbleSingleton getDs(){
if(ds==null){
try {
//模拟初始化对象的准备时间
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (DubbleSingleton.class) {
if(ds==null){
ds = new DubbleSingleton();
}
}
}
return ds;
}

public static void main(String[] args) {
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println(DubbleSingleton.getDs().hashCode());
}
},"t1");
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println(DubbleSingleton.getDs().hashCode());
}
},"t2");
Thread t3 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println(DubbleSingleton.getDs().hashCode());
}
},"t3");
t1.start();
t2.start();
t3.start();
}
}


static inner class

public class InnerSingleton {

//静态内部类,实例化对象
private static class Singleton{
private static Singleton single = new Singleton();
}

private static Singleton getInstance(){
return Singleton.single;
}

}


同步类容器和并发类容器

同步类容器都是线程安全的,但在某些场景下可能需要加锁来保护复合操作。复合类操作如:迭代(反复访问元素,遍历容器中所有的元素)、跳转(根据指定顺序找到当前元素的下一个元素)、以及条件运算。这些复合操作在多线程并发的修改容器时,可能会表现出意外的行为,最经典的就是ConcurrentModificationException,原因是当容器迭代的过程中,被并发修改了内容,这是由于早期迭代器设计的时候并没有考虑并发修改的问题。

同步类容器:比如古老的Vector、HashTable。这些容器的同步功能都是有JDK的Collections.synchronized***等工厂方法创建实现的。其底层的机制无非是用传统的synchronized关键字对每个共用的方法进行同步,使得每次只能有一个线程访问容器的状态。这明显不满足互联网高并发的要求,在线程安全的同时也必须要有足够好的性能。

public class Tickets {

public static void main(String[] args) {
//初始化火车票池并添加火车票:避免线程同步可采取vector替代ArrayList HashTable替代HashMap
final Vector<String> tickets = new Vector<String>();
//将集合转换为线程安全的
//Map<String,String> map = Collections.synchronizedMap(new HashMap<String,String>());

for(int i=1;i<=1000;i++){
tickets.add("火车票"+i);
}

for(int i=1;i<=10;i++){
new Thread("线程"+i){
public void run(){
while(true){
if(tickets.isEmpty())break;
System.out.println(Thread.currentThread().getName()+"---"+tickets.remove(0));
}
}
}.start();
}
}
}


**并发类容器:**jdk5.0以后提供了多种并发类容器来替代同步类容器从而改善性能。同步类容器的状态都是串行化的。他们虽然实现了线程安全,但是严重降低了并发性,在多线程环境下严重降低了应用程序的吞吐量。

并发类容器是专门针对并发设计的,使用ConcurrentHashMap来代替基于散列的传统的HashTable,而且在ConcurrentHashMap中添加了一些常见复合操作的支持。以及使用了CopyOnWriteArrayList代替Vector,并发的CopyOnWriteArraySet,以及并发的Queue,ConcurrentLinkedQueue和LinkedBlockingQueue,前者是高性能的队列,后者是以阻塞形式的队列,具体实现Queue还有很多,例如ArrayBlockingQueue、PriorityBlockingQueue、SynchronousQueue等。

ConcurrentMap

ConcurrentMap接口下有两个重要的实现:

- ConcurrentHashMap

- ConcurrentSkipListMap(支持并发排序功能,弥补ConcurrentHashMap)

ConcurrentHashMap内部使用段(Segment)来表示这些不同的部分,每个段其实就是一个小的HashTable,它们有自己的锁。只要多个修改操作发生在不同的段上,它们就可以并发进行。把一个整体分成了16个段(Segment)。也就是最高支持16个线程的并发修改操作。这也是多线程场景时减少锁的粒度从而降低锁竞争的一种方案。并且代码中大多共享变量使用volatile关键字声明,目的是第一时间内获取修改的内容,性能非常好。

public class UseConcurrentMap {

public static void main(String[] args) {
ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String,Object>();
chm.put("k1", "v1");
chm.put("k2", "v2");
chm.put("k3", "v3");
chm.putIfAbsent("k4", "vvvv");

for(Map.Entry<String, Object> me:chm.entrySet()){
System.out.println("key: "+me.getKey()+",value:"+me.getValue());
}

}

}


CopyOnWrite容器(读多写少的场景中使用)

CopyOnWrite容器简称COW,是一种用于程序设计中的优化策略。JDK里的COW容器有两种:

- CopyOnWriteArrayList

- CopyOnWriteArraySet

COW容器非常有用,可以在非常多的并发场景中使用到。

CopyOnWrite容器即写时复制的容器。通俗的理解就是当我们在往一个容器中添加元素的时候,不直接往当前的容器中添加,而是先将当前的容器进行Copy,复制出一个新的容器,然后向新的容器里添加元素,添加完元素之后,再将原来容器的引用指向新的容器。这样做的好处是我们可以对CopyOnWrite容器进行并发的读,而不需要加锁,因为当前容器不会添加任何元素。所以CopyOnWrite容器是一种读写分离的思想,读和写不同的容器。

public class UseCopyOnWrite {

CopyOnWriteArrayList<String> cwal = new CopyOnWriteArrayList<String>();
CopyOnWriteArraySet<String> cwas = new CopyOnWriteArraySet<String>();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息