JDK5線程并發(fā)包
1)AtomicInteger
使用原子方式更新int值
2)創(chuàng)建線程池
a)創(chuàng)建固定大小的線程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);//創(chuàng)建一個(gè)有10個(gè)線程的線程池
b)創(chuàng)建緩存線程池
Executors.newCachedThreadPool();
創(chuàng)建一個(gè)可根據(jù)需要?jiǎng)?chuàng)建新線程的線程池,可自動(dòng)調(diào)整線程的多少
c)創(chuàng)建單線程的線程池
Executors.newSingleThreadExecutor();
該線程池里面只有一個(gè)線程,如果死掉了也可以自動(dòng)再創(chuàng)建一個(gè),保證永遠(yuǎn)有一個(gè)
d)創(chuàng)建一個(gè)線程池,它可安排在給定延遲后運(yùn)行命令或者定期地執(zhí)行
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);
threadPool.schedule(Runnable command,long delay,TimeUnit unit)
創(chuàng)建并執(zhí)行在給定延遲后啟用的一次性操作
threadPool.scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)
創(chuàng)建并執(zhí)行一個(gè)在給定初始延遲后首次啟用的定期操作,后續(xù)操作具有給定的周期.
也就是將在initialDelay后開(kāi)始執(zhí)行,然后在initialDelay+period后執(zhí)行,接著在initialDelay + 2 * period后執(zhí)行,依此類(lèi)推
不管哪種創(chuàng)建方式其實(shí)都是由ThreadPoolExecutor類(lèi)來(lái)實(shí)現(xiàn)的
3)Callable&Future
a)Future取得的結(jié)果類(lèi)型和Callable返回的結(jié)果類(lèi)型必須一致,這是通過(guò)泛型來(lái)實(shí)現(xiàn)的。
b)Callable要采用ExecutorSevice的submit方法提交,返回的future對(duì)象可以取消任務(wù)。
c)CompletionService用于提交一組Callable任務(wù),其take方法返回已完成的一個(gè)Callable任務(wù)對(duì)應(yīng)的Future對(duì)象。
4)Lock&Condition
Lock ---> synchronized
Lock lock = new ReentrantLock();
ReadWriteLock rwlock = new ReentrantReadWriteLock();
private Condition condition = lock.newCondition();
condition.await(); ---> wait()
condition.signal(); ---> notify()
5)Semaphore
final Semaphore semaphore = new Semaphore(3);
6)CyclicBarrier
7)CountDownLatch
8)Exchanger
9)ArrayBlockingQueue(阻塞隊(duì)列)
10)ConcurrentHashMap
CopyOnWriteArrayList
CopyOnWriteArraySet