首页 > 其他 > 详细

并发编程学习(二)

时间:2018-08-18 16:49:32      阅读:140      评论:0      收藏:0      [点我收藏+]

对象发生变化锁失效,对象内的属性改变,锁不会失效。

ConcurrentModificationException出现的原因是因为以前的容器没有考虑到并发情况下读取的时候删除元素而引起的。

wait/notify:

   wait和notify是Object类的方法,wait会释放锁,notify不释放锁。这两个必须配合synchronized一同使用。
并发容器:

ConcurrentHashMap:

    内部使用段(segment)来表示这些不同部分,每个段其实就是一个小的hashtable,各自有锁,共分为16个段,最高支持16个线程,代码中大多共享变量使用volatile。

CopyOnWrite:

          写时复制,是在写完

ConcurrentLinkedQueue:

         是一个适用于高并发场景下的队列,通过无锁的方式,实现了高并发状态下的高性能,性能好于blockingQueue,队列无界,先进先出,不允许有null值。

  add()和offer()都是加入元素,poll()和peek()都是取头部数据,区别在于前都会删除元素,后者不会。

ArrayBlockingQueue:

         必须要定义长度,也叫有界队列。

LinkedBlockingQueue:

            无界队列,内部采用分离锁(读写分离)。适用于高并发。

SynchronousQueue:

           一种没有缓冲的队列,生产者产生的数据直接被消费者消费。

PriorityBlockingQueue:

         基于优先级的阻塞队列。

DelayQueue:

      带有延迟时间的Queue。

Executor框架:

  newFixedThreadPool():固定数量的线程池,有任务提交就执行,没有线程空闲就暂缓在一个任务队列中。

  newSingleThreadPool():创建一个线程的线程池,若空闲就执行,没有就存在任务队列中。

  newCachedThreadPool():返回一个根据实际情况调整线程个数的线程池,不限制最大线程数量,如果没有任务60s就回收。

  newScheduledThreadPool():返回一个ScheduledExecutorService对象,可以指定线程数量。可做定时job。

线程池底层是调用ThreadPoolExecutor()来实现的。

 public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}



public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));//父类也是ThreadPoolExecutor
}
 
 

ThreadPoolExecutor方法内参数说明:

public ThreadPoolExecutor(int corePoolSize,//核心线程数
int maximumPoolSize,//最大线程数
long keepAliveTime, //空闲存活时间
TimeUnit unit, //时间单位 
BlockingQueue<Runnable> workQueue,//任务队列
ThreadFactory threadFactory,
RejectedExecutionHandler handler)

 

 

 

 

 

 

并发编程学习(二)

原文:https://www.cnblogs.com/javage/p/9497582.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!