在 java 5.0 提供了 java.util.concurrent (簡稱JUC )包,在此包中增加了在并發編程中很常用的實用工具類,用于定義類似于線程的自定義子系統,包括線程池、異步 IO 和輕量級任務框架。提供可調的、靈活的線程池。還提供了設計用于多線程上下文中的 Collection 實現等。
內存可見性
內存可見性(Memory Visibility)是指當某個線程正在使用對象狀態而另一個線程在同時修改該狀態,需要確保當一個線程修改了對象狀態后,其他線程能夠看到發生的狀態變化。
可見性錯誤是指當讀操作與寫操作在不同的線程中執行時,我們無法確保執行讀操作的線程能適時地看到其他線程寫入的值,有時甚至是根本不可能的事情。
我們可以通過同步來保證對象被安全地發布。除此之外我們也可以使用一種更加輕量級的 volatile 變量。
volatile 關鍵字
Java 提供了一種稍弱的同步機制,即 volatile 變量,用來確保將變量的更新操作通知到其他線程,可以保證內存中的數據可見??梢詫?volatile 看做一個輕量級的鎖,但是又與鎖有些不同:
對于多線程,不是一種互斥關系不能保證變量狀態的“原子性操作”public class TestVolatile { public static void main(String[] args){ ThreadDemo td=new ThreadDemo(); new Thread(td).start(); while(true){ if(td.isFlag()){ System.out.二、原子變量 、CAS原子變量:jdk1.5 后 java.util.concurrent.atomic 類的小工具包,支持在單個變量上解除鎖的線程安全編程,包下提供了常用的原子變量: - AtomicBoolean 、AtomicInteger 、AtomicLong 、 AtomicReference - AtomicIntegerArray 、AtomicLongArray - AtomicMarkableReference - AtomicReferenceArray - AtomicStampedReference
1.類中的變量都是volatile類型:保證內存可見性 2.使用CAS算法:保證數據的原子性
CAS (Compare-And-Swap) 是一種硬件對并發的支持,針對多處理器操作而設計的處理器中的一種特殊指令,用于管理對共享數據的并發訪問。 CAS 是一種無鎖的非阻塞算法的實現。 CAS包含三個操作數: 內存值 V 預估值 A 更新值 B 當且僅當V==A時,B的值才更新給A,否則將不做任何操作。
public class TestAtomicDemo { public static void main(String[] args) { AtomicDemo ad = new AtomicDemo(); for (int i = 0; i < 10; i++) { new Thread(ad).start(); } }}class AtomicDemo implements Runnable{// private volatile int serialNumber = 0; private AtomicInteger serialNumber = new AtomicInteger(0); @Override public void run() { try { Thread.sleep(200); } catch (InterruptedException e) { } System.out.println(getSerialNumber()); } public int getSerialNumber(){ return serialNumber.getAndIncrement();//i++ 實際是int temp=i;i=i+1;i=temp; 需要原子性操作 }}使用synchronized方法模擬CAS 算法,實際是由硬件機制完成的,用10個線程代表對內存中數據的10次修改請求。只有上個線程修改完,這個線程從內存中獲取的內存值當成期望值,才等于內存值,才能對內存值進行修改。
public class TestCompareAndSwap { public static void main(String[] args) { final CompareAndSwap cas=new CompareAndSwap(); for(int i=0;i<10;i++){ new Thread(new Runnable(){ @Override public void run() { int expectedValue=cas.get(); boolean b=cas.compareAndSwap(expectedValue, (int)(Math.random()*101)); System.out.println(b); } }).start(); } }}class CompareAndSwap{ private int value;//內存值 //獲取內存值 public synchronized int get(){ return value; } //比較 public synchronized boolean compareAndSwap(int expectedValue,int newValue){ int oldValue=value;//線程讀取內存值,與預估值比較 if(oldValue==expectedValue){ this.value=newValue; return true; } return false; }}HashMap 線程不安全 Hashtable 內部采用獨占鎖,線程安全,但效率低 ConcurrentHashMap同步容器類是java5 新增的一個線程安全的哈希表,效率介于HashMap和Hashtable之間。內部采用“鎖分段”機制。
java.util.concurrent 包還提供了設計用于多線程上下文中的Collection實現:
當期望許多線程訪問一個給定 collection 時, ConcurrentHashMap 通常優于同步的 HashMap, ConcurrentSkipListMap 通常優于同步的 TreeMap ConcurrentSkipListSet通常優于同步的 TreeSet.
當期望的讀數和遍歷遠遠大于列表的更新數時, CopyOnWriteArrayList 優于同步的 ArrayList。因為每次添加時都會進行復制,開銷非常的大,并發迭代操作多時 ,選擇。
CountDownLatch 一個同步輔助類,在完成一組正在其他線程中執行的操作之前,它允許一個或多個線程一直等待。
閉鎖可以延遲線程的進度直到其到達終止狀態,閉鎖可以用來確保某些活動直到其他活動都完成才繼續執行: ? 確保某個計算在其需要的所有資源都被初始化之后才繼續執行; ? 確保某個服務在其依賴的所有其他服務都已經啟動之后才啟動; ? 等待直到某個操作所有參與者都準備就緒再繼續執行。
/* * CountDownLatch:閉鎖,在完成某些運算時,只有其他所有線程的運算全部完成,當前運算才繼續執行 */public class TestCountDownLatch { public static void main(String[] args) { final CountDownLatch latch=new CountDownLatch(50); LatchDemo ld=new LatchDemo(latch); long start=System.currentTimeMillis(); for(int i=0;i<50;i++){ new Thread(ld).start(); } try { latch.await(); //直到50個人子線程都執行完,latch的值減到0時,才往下執行 } catch (InterruptedException e) { e.printStackTrace(); } long end=System.currentTimeMillis(); System.out.println("耗費時間為:"+(end-start)); }}class LatchDemo implements Runnable{ private CountDownLatch latch; public LatchDemo(CountDownLatch latch){ this.latch=latch; } @Override public void run() { try{ for(int i=0;i<50000;i++){ if(i%2==0){ System.out.println(i); } } }finally{ latch.countDown();//latch的值減一 } }}Java 5.0 在 java.util.concurrent 提供了一個新的創建執行線程的方式:Callable 接口
實現Callable 接口,相較于實現 Runnable接口的方式,方法可以有返回值,并且可以拋出異常。
Callable 需要依賴FutureTask ,用于接收返回值,FutureTask 也可以用作閉鎖。
/* * 一、創建執行線程的方式三:實現Callable接口。相較于實現Runnable接口的方式,方法可以有返回值,并且可以拋出異常。 * 二、執行Callable方式,需要FutureTask實現類的支持,用于接收運算結果。FutureTask是Future接口的實現類 */public class TestCallable { public static void main(String[] args) { ThreadDemo2 td=new ThreadDemo2(); //1.執行Callable方式,需要FutureTask實現類的支持,用于接收運行結果。 FutureTask<Integer> result=new FutureTask<>(td); new Thread(result).start(); //2.接收線程運算后的結果 try { Integer sum = result.get();//FutureTask 可用于 閉鎖 當子線程執行完畢,才會執行此后語句 System.out.println(sum); System.out.println("----------------------"); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }}class ThreadDemo2 implements Callable<Integer>{ @Override public Integer call() throws Exception { int sum=0; for(int i=0;i<=100000;i++){ sum+=i; } return sum; }}在 Java 5.0 之前,協調共享對象的訪問時可以使用的機制只有 synchronized 和 volatile 。Java 5.0 后增加了一些新的機制,但并不是一種替代內置鎖的方法,而是當內置鎖不適用時,作為一種可選擇的高級功能。
ReentrantLock 實現了 Lock 接口,并提供了與synchronized 相同的互斥性和內存可見性。但相較于synchronized 提供了更高的處理鎖的靈活性。
/* * 一、用于解決多線程安全問題的方式: * synchronized:隱式鎖 * 1、同步代碼塊 * 2、同步方法 * jdk 1.5后 * 3、同步鎖 Lock * 注意:是一個顯式鎖,通過lock()方式上鎖,必須通過unlock()方法釋放鎖 */public class TestLock { public static void main(String[] args) { Ticket ticket=new Ticket(); new Thread(ticket,"1號窗口").start(); new Thread(ticket,"2號窗口").start(); new Thread(ticket,"3號窗口").start(); }}class Ticket implements Runnable{ private int tick=100; private Lock lock=new ReentrantLock(); @Override public void run() { while(true){ lock.lock(); try{ if(tick>0){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"完成售票為:"+--tick); } else{ break; } }finally{ lock.unlock();//釋放鎖一定要放在finally里,保證一定執行 } } }}/* * 生產者和消費者案例,優化,防止出現虛假喚醒,線程無法停止 */public class TestProductorAndConsumer { public static void main(String[] args) { Clerk clerk=new Clerk(); Productor pro=new Productor(clerk); Consumer cus=new Consumer(clerk); new Thread(pro,"生產者 A").start(); new Thread(cus,"消費者 B").start(); new Thread(pro,"生產者 C").start(); new Thread(cus,"消費者 D").start(); }}//店員 假如只有一個商品位置class Clerk{ private int product=0; //進貨 public synchronized void get(){ while(product>=1){//為了避免虛假喚醒問題,應該總是使用在循環中 System.out.println("產品已滿!"); try{ this.wait(); }catch(InterruptedException e){ } } System.out.println(Thread.currentThread().getName()+" : "+ ++product); this.notifyAll(); } //賣貨 public synchronized void sale(){ while(product<=0){ System.out.println("缺貨!"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+" : "+ --product); this.notifyAll(); }}//生產者class Productor implements Runnable{ private Clerk clerk; public Productor(Clerk clerk){ this.clerk=clerk; } @Override public void run() { for(int i=0;i<20;i++){ try{ Thread.sleep(200); }catch(InterruptedException e){ } clerk.get(); } }}//消費者class Consumer implements Runnable{ private Clerk clerk; public Consumer(Clerk clerk){ this.clerk=clerk; } @Override public void run() { for(int i=0;i<20;i++){ clerk.sale(); } }}Condition 接口描述了可能會與鎖有關聯的條件變量。這些變量在用法上與使用 Object.wait 訪問的隱式監視器類似,但提供了更強大的功能。需要特別指出的是,單個 Lock 可能與多個 Condition 對象關聯。為了避免兼容性問題,Condition 方法的名稱與對應的 Object 版本中的不同。
在 Condition 對象中,與 wait、notify 和 notifyAll 方法對應的分別是await、signal 和 signalAll。
Condition 實例實質上被綁定到一個鎖上。要為特定 Lock 實例獲得Condition 實例,請使用其 newCondition() 方法。
public class TestProductorAndConsumerForLock { public static void main(String[] args) { Clerk clerk=new Clerk(); Productor pro=new Productor(clerk); Consumer cus=new Consumer(clerk); new Thread(pro,"生產者 A").start(); new Thread(cus,"消費者 B").start(); new Thread(pro,"生產者 C").start(); new Thread(cus,"消費者 D").start(); }}//店員 假如只有一個商品位置class Clerk{ private int product=0; private Lock lock=new ReentrantLock(); private Condition condition=lock.newCondition(); //進貨 public void get(){ lock.lock(); try{ while(product>=1){//為了避免虛假喚醒問題,應該總是使用在循環中 System.out.println("產品已滿!"); try{ condition.await();//this.wait(); }catch(InterruptedException e){ } } System.out.println(Thread.currentThread().getName()+" : "+ ++product); condition.signalAll();//this.notifyAll(); }finally{ lock.unlock(); } } //賣貨 public void sale(){ lock.lock(); try{ while(product<=0){ System.out.println("缺貨!"); try { condition.await();//this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+" : "+ --product); condition.signalAll();//this.notifyAll(); }finally{ lock.unlock(); } }}//生產者class Productor implements Runnable{ private Clerk clerk; public Productor(Clerk clerk){ this.clerk=clerk; } @Override public void run() { for(int i=0;i<20;i++){ try{ Thread.sleep(200); }catch(InterruptedException e){ } clerk.get(); } }}//消費者class Consumer implements Runnable{ private Clerk clerk; public Consumer(Clerk clerk){ this.clerk=clerk; } @Override public void run() { for(int i=0;i<20;i++){ clerk.sale(); } }}編寫一個程序,開啟 3 個線程,這三個線程的 ID 分別為A、B、C,每個線程將自己的 ID 在屏幕上打印 10 遍,要求輸出的結果必須按順序顯示。如:ABCABCABC…… 依次遞歸
public class TestABCAlternate { public static void main(String[] args) { AlternateDemo ad=new AlternateDemo(); new Thread(new Runnable(){ @Override public void run() { for(int i=1;i<=20;i++){ ad.loopA(i); } } },"A").start(); new Thread(new Runnable(){ @Override public void run() { for(int i=1;i<=20;i++){ ad.loopB(i); } } },"B").start(); new Thread(new Runnable(){ @Override public void run() { for(int i=1;i<=20;i++){ ad.loopC(i); System.out.println("-----------------------------------"); } } },"C").start(); }}class AlternateDemo{ private int number=1;//當前正在執行線程的標記 private Lock lock=new ReentrantLock(); private Condition condition1=lock.newCondition(); private Condition condition2=lock.newCondition(); private Condition condition3=lock.newCondition(); /* * @param totalLoop:循環第幾輪 */ public void loopA(int totalLoop){ lock.lock(); try{ //1.判斷 if(number!=1){ condition1.await(); } //2.打印 System.out.println(Thread.currentThread().getName()+"/t"+totalLoop); //3.喚醒 number=2; condition2.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally{ lock.unlock(); } } public void loopB(int totalLoop){ lock.lock(); try{ //1.判斷 if(number!=2){ condition2.await(); } //2.打印 System.out.println(Thread.currentThread().getName()+"/t"+totalLoop); //3.喚醒 number=3; condition3.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally{ lock.unlock(); } } public void loopC(int totalLoop){ lock.lock(); try{ //1.判斷 if(number!=3){ condition3.await(); } //2.打印 System.out.println(Thread.currentThread().getName()+"/t"+totalLoop); //3.喚醒 number=1; condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally{ lock.unlock(); } }}ReadWriteLock 維護了一對相關的鎖,一個用于只讀操作,另一個用于寫入操作。只要沒有 writer,讀取鎖可以由多個 reader 線程同時保持。寫入鎖是獨占的。
ReadWriteLock 讀取操作通常不會改變共享資源,但執行寫入操作時,必須獨占方式來獲取鎖。對于讀取操作占多數的數據結構。 ReadWriteLock 能提供比獨占鎖更高的并發性。而對于只讀的數據結構,其中包含的不變性可以完全不需要考慮加鎖操作。
/* * 1.ReadWriteLock:讀寫鎖 * 寫寫|讀寫 需要"互斥" * 讀讀 不需要"互斥" */public class TestReadWriteLock { public static void main(String[] args) { ReadWriteLockDemo rw=new ReadWriteLockDemo(); new Thread(new Runnable() { @Override public void run() { rw.set((int)(Math.random()*101)); } },"Write").start(); for(int i=0;i<100;i++){ new Thread(new Runnable() { @Override public void run() { rw.get(); } }).start(); } }}class ReadWriteLockDemo{ private int number=0; private ReadWriteLock lock=new ReentrantReadWriteLock(); //讀 public void get(){ lock.readLock().lock();//上鎖 try{ System.out.println(Thread.currentThread().getName()+" : "+number); }finally{ lock.readLock().unlock();//釋放鎖 } } //寫 public void set(int number){ lock.writeLock().lock(); try{ System.out.println(Thread.currentThread().getName()); this.number=number; }finally{ lock.writeLock().unlock(); } }}獲取線程第四種方法。 線程池可以解決兩個不同問題:由于減少了每個任務調用的開銷,它們通??梢栽趫绦写罅慨惒饺蝿諘r提供增強的性能,并且還可以提供綁定和管理資源(包括執行任務集時使用的線程)的方法。每個 ThreadPoolExecutor 還維護著一些基本的統計數據,如完成的任務數。
為了便于跨大量上下文使用,此類提供了很多可調整的參數和擴展鉤子 (hook)。但是,強烈建議程序員使用較為方便的 Executors 工廠方法 :
Executors.newCachedThreadPool()(無界線程池,可以進行自動線程回收)Executors.newFixedThreadPool(int)(固定大小線程池)Executors.newSingleThreadExecutor()(單個后臺線程)它們均為大多數使用場景預定義了設置。
/* * 一、線程池:提供了一個線程隊列,隊列中保存著所有等待狀態的線程。避免了創建與銷毀額外開銷,提高了響應的速度。 * 二、線程池的體系結構: * java.util.concurrent.Executor:負責線程的使用與調度的根接口 * |--**ExecutorService 子接口:線程池的主要接口 * |--ThreadPoolExecutor 線程池的實現類 * |--ScheduledExecutorService 子接口:負責線程的調度 * |--ScheduledThreadPoolExecutor:繼承ThreadPoolExecutor,實現ScheduledExecutorService接口 * 三、工具類:Executors * 方法有: * ExecutorService newFixedThreadPool(): 創建固定大小的線程池 * ExecutorService newCachedThreadPool():緩存線程池,線程池的數量不固定,可以根據需要自動的更改數量。 * ExecutorService newSingleThreadExecutor():創建單個線程池。線程池中只有一個線程 * * ScheduledExecutorService newScheduledThreadPool():創建固定大小的線程,可以延遲或定時的執行任務。 * */public class TestThreadPool { public static void main(String[] args) { //1.創建線程池 ExecutorService pool=Executors.newFixedThreadPool(5); List<Future<Integer>> list=new ArrayList<>(); for (int i = 0; i < 10; i++) { Future<Integer> future=pool.submit(new Callable<Integer>(){ @Override public Integer call() throws Exception { int sum=0; for(int i=0;i<=100;i++){ sum+=i; } return sum; } }); list.add(future); } pool.shutdown(); for(Future<Integer> future:list){ try { System.out.println(future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }}Fork/Join 框架:就是在必要的情況下,將一個大任務,進行拆分(fork)成若干個小任務(拆到不可再拆時),再將一個個的小任務運算的結果進行 join 匯總。
Fork/Join 框架與線程池的區別: 采用 “工作竊取”模式(work-stealing):相對于一般的線程池實現,fork/join框架的優勢體現在對其中包含的任務的處理方式上.在一般的線程池中,如果一個線程正在執行的任務由于某些原因無法繼續運行,那么該線程會處于等待狀態。而在fork/join框架實現中,如果某個子問題由于等待另外一個子問題 的完成而無法繼續運行。那么處理該子問題的線程會主動尋找其他尚未運行的子問題來執行.這種方式減少了線程的等待時間,提高了性能。
public class TestForkJoinPool { public static void main(String[] args) { Instant start=Instant.now(); ForkJoinPool pool=new ForkJoinPool(); ForkJoinTask<Long> task=new ForkJoinSumCalculate(0L, 50000000000L); Long sum=pool.invoke(task); System.out.println(sum); Instant end=Instant.now(); System.out.println("耗費時間為:"+Duration.between(start, end).toMillis());//耗費時間為:21020 } //一般的方法 @Test public void test1(){ Instant start=Instant.now(); long sum=0L; for(long i=0L;i<=50000000000L;i++){ sum+=i; } System.out.println(sum); Instant end=Instant.now(); System.out.println("耗費時間為:"+Duration.between(start, end).toMillis());//耗費時間為:27040 } //java8 新特性 @Test public void test2(){ Instant start=Instant.now(); Long sum=LongStream.rangeClosed(0L,50000000000L).parallel().reduce(0L, Long::sum); System.out.println(sum); Instant end=Instant.now(); System.out.println("耗費時間為:"+Duration.between(start, end).toMillis());//耗費時間為:14281 }}class ForkJoinSumCalculate extends RecursiveTask<Long>{ private static final long serialVersionUID=-54565646543212315L; private long start; private long end; private static final long THURSHOLD=10000L;//臨界值,小于這個值就不拆了,直接運算 public ForkJoinSumCalculate(long start,long end){ this.start=start; this.end=end; } @Override protected Long compute() { long length=end-start; if(length<=THURSHOLD){ long sum=0L; for(long i=start;i<=end;i++){ sum+=i; } return sum; }else{ //進行拆分,同時壓入線程隊列 long middle=(start+end)/2; ForkJoinSumCalculate left=new ForkJoinSumCalculate(start, middle); left.fork(); ForkJoinSumCalculate right=new ForkJoinSumCalculate(middle+1, end); right.fork(); return left.join()+right.join(); } }}新聞熱點
疑難解答