1.Volatile關(guān)鍵字
package cn.zzu.wcj.juc;/** * * @author WangChengJian * volatile關(guān)鍵字:當(dāng)多個(gè)線程進(jìn)行操作共享數(shù)據(jù)時(shí),可以保證內(nèi)存中的數(shù)據(jù)的可見性 * 相較于synchronized關(guān)鍵字是一種較為輕量級(jí)的同步策略 * 注意: * 1.volatile不具備互斥性 * 2.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.2.原子變量package cn.zzu.wcj.juc;import java.util.concurrent.atomic.AtomicInteger;/* * 一、i++ 的原子性問題:i++ 的操作實(shí)際上分為三個(gè)步驟“讀-改-寫” * int i = 10; * i = i++; //10 * * int temp = i; * i = i + 1; * i = temp; * * 二、原子變量:在 java.util.concurrent.atomic 包下提供了一些原子變量。 * 1. volatile 保證內(nèi)存可見性 * 2. CAS(Compare-And-Swap) 算法保證數(shù)據(jù)變量的原子性 * CAS 算法是硬件對于并發(fā)操作的支持 * CAS 包含了三個(gè)操作數(shù): * ①內(nèi)存值 V * ②預(yù)估值 A * ③更新值 B * 當(dāng)且僅當(dāng) V == A 時(shí), V = B; 否則,不會(huì)執(zhí)行任何操作。 */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() ; @Override public void run() { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getSerialNumber()); } public int getSerialNumber() { return serialNumber.getAndIncrement(); }}3.閉鎖
package cn.zzu.wcj.juc;import java.util.concurrent.CountDownLatch;/* * CountDownLatch :閉鎖,在完成某些運(yùn)算時(shí),只有其他所有線程的運(yùn)算全部完成,當(dāng)前運(yùn)算才繼續(xù)執(zhí)行 */public class TestCountDownLatch { public static void main(String[] args) throws Exception { final CountDownLatch latch=new CountDownLatch(10) ; LatchDemo ld=new LatchDemo(latch) ; long start=System.currentTimeMillis() ; for(int i=0;i<10;i++){ new Thread(ld).start(); } latch.await(); long end=System.currentTimeMillis() ; System.out.println("耗時(shí):"+(end-start)); }}class LatchDemo implements Runnable { private CountDownLatch latch ; public LatchDemo(CountDownLatch latch){ this.latch=latch ; } @Override public void run() { synchronized (this) { try{ for (int i = 0; i < 6000; i++) { if(i%2==0){ System.out.println(i); } } }finally{ latch.countDown(); } } }}4.線程的第三種創(chuàng)建方式
package cn.zzu.wcj.juc;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;/* * 一、創(chuàng)建執(zhí)行線程的方式三:實(shí)現(xiàn) Callable 接口。 相較于實(shí)現(xiàn) Runnable 接口的方式,方法可以有返回值,并且可以拋出異常。 * * 二、執(zhí)行 Callable 方式,需要 FutureTask 實(shí)現(xiàn)類的支持,用于接收運(yùn)算結(jié)果。 FutureTask 是 Future 接口的實(shí)現(xiàn)類 */public class TestCallable { public static void main(String[] args)throws Exception { CallThread ct=new CallThread() ; //1.執(zhí)行 Callable 方式,需要 FutureTask 實(shí)現(xiàn)類的支持,用于接收運(yùn)算結(jié)果。 FutureTask<Integer> result = new FutureTask<Integer>(ct); new Thread(result).start(); //2.接收線程運(yùn)算后的結(jié)果 Integer sum=result.get() ; //FutureTask 可用于 閉鎖 System.out.println("sum="+sum); System.out.println("-----------------------------"); } }class CallThread implements Callable<Integer>{ @Override public Integer call() throws Exception { Integer sum=0 ; for (int i = 0; i < 10; i++) { System.out.println(i); sum=sum+i ; } return sum; }}5.線程鎖
package cn.zzu.wcj.juc;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/* * 一、用于解決多線程安全問題的方式: * * synchronized:隱式鎖 * 1. 同步代碼塊 * * 2. 同步方法 * * jdk 1.5 后: * 3. 同步鎖 Lock * 注意:是一個(gè)顯示鎖,需要通過 lock() 方法上鎖,必須通過 unlock() 方法進(jìn)行釋放鎖 */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 Integer ticket = 10 ; private Lock lock=new ReentrantLock() ; @Override public void run() { while(true){ lock.lock(); //上鎖 try{ if(this.ticket > 0){ try { Thread.sleep(200); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + " 完成售票,余票為:" + --this.ticket); } }finally{ lock.unlock(); //釋放鎖 } } }}6.線程八鎖
package cn.zzu.wcj.juc;/* * 題目:判斷打印的 "one" or "two" ? * * 1. 兩個(gè)普通同步方法,兩個(gè)線程,標(biāo)準(zhǔn)打印, 打印? //one two * 2. 新增 Thread.sleep() 給 getOne() ,打印? //one two * 3. 新增普通方法 getThree() , 打印? //three one two * 4. 兩個(gè)普通同步方法,兩個(gè) Number 對象,打印? //two one * 5. 修改 getOne() 為靜態(tài)同步方法,打印? //two one * 6. 修改兩個(gè)方法均為靜態(tài)同步方法,一個(gè) Number 對象? //one two * 7. 一個(gè)靜態(tài)同步方法,一個(gè)非靜態(tài)同步方法,兩個(gè) Number 對象? //two one * 8. 兩個(gè)靜態(tài)同步方法,兩個(gè) Number 對象? //one two * * 線程八鎖的關(guān)鍵: * ①非靜態(tài)方法的鎖默認(rèn)為 this, 靜態(tài)方法的鎖為 對應(yīng)的 Class 實(shí)例 * ②某一個(gè)時(shí)刻內(nèi),只能有一個(gè)線程持有鎖,無論幾個(gè)方法。 */public class TestThread8Monitor { public static void main(String[] args) { final Number number=new Number() ; final Number number2=new Number() ; new Thread(new Runnable() { @Override public void run() { number.getOne(); } }).start(); new Thread(new Runnable() { @Override public void run() { number2.getTwo(); } }).start();// new Thread(new Runnable() {// @Override// public void run() {// number.getTree();// }// }).start(); }}class Number{ public static synchronized void getOne(){ try{ Thread.sleep(2000); }catch(Exception e){} System.out.println("one"); } public static synchronized void getTwo(){ System.out.println("two"); } public void getTree(){ System.out.println("three"); }}7.讀寫鎖
package cn.zzu.wcj.juc;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;/* * 1. ReadWriteLock : 讀寫鎖 * * 寫寫/讀寫 需要“互斥” * 讀讀 不需要互斥 * */public class TestReadWriteLock { public static void main(String[] args) { final ReadWriteLockDemo rw=new ReadWriteLockDemo() ; for(int i=0;i<10;i++){ final int x=i+1 ; new Thread(new Runnable() { @Override public void run() { rw.set(x); } },"寫線程"+i).start(); } for(int j=0;j<10;j++){ new Thread(new Runnable() { @Override public void run() { rw.get(); } },"讀線程-"+j).start(); } }}class ReadWriteLockDemo{ private Integer num=0 ; private ReadWriteLock lock=new ReentrantReadWriteLock() ; //讀寫鎖 public void get(){ this.lock.readLock().lock(); try{ System.out.println(Thread.currentThread().getName()+"-->num:"+num); }finally{ this.lock.readLock().unlock(); } } public void set(Integer num){ this.lock.writeLock().lock(); try{ this.num=num ; System.out.println(Thread.currentThread().getName()+"-->num:"+num); }finally{ this.lock.writeLock().unlock(); } }}8.線程池
package cn.zzu.wcj.juc;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/* * 一、線程池:提供了一個(gè)線程隊(duì)列,隊(duì)列中保存著所有等待狀態(tài)的線程。避免了創(chuàng)建與銷毀額外開銷,提高了響應(yīng)的速度。 * * 二、線程池的體系結(jié)構(gòu): * java.util.concurrent.Executor : 負(fù)責(zé)線程的使用與調(diào)度的根接口 * |--**ExecutorService 子接口: 線程池的主要接口 * |--ThreadPoolExecutor 線程池的實(shí)現(xiàn)類 * |--ScheduledExecutorService 子接口:負(fù)責(zé)線程的調(diào)度 * |--ScheduledThreadPoolExecutor :繼承 ThreadPoolExecutor, 實(shí)現(xiàn) ScheduledExecutorService * * 三、工具類 : Executors * ExecutorService newFixedThreadPool() : 創(chuàng)建固定大小的線程池 * ExecutorService newCachedThreadPool() : 緩存線程池,線程池的數(shù)量不固定,可以根據(jù)需求自動(dòng)的更改數(shù)量。 * ExecutorService newSingleThreadExecutor() : 創(chuàng)建單個(gè)線程池。線程池中只有一個(gè)線程 * * ScheduledExecutorService newScheduledThreadPool() : 創(chuàng)建固定大小的線程,可以延遲或定時(shí)的執(zhí)行任務(wù)。 */public class TestThreadPool { public static void main(String[] args)throws Exception { //1.創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(8) ; //2.為線程池中的線程分配任務(wù) //TaskThread task=new TaskThread() ; //pool.submit(task) ; List<Future<Integer>> results=new ArrayList<Future<Integer>>() ; for(int i=0;i<10;i++){ Future<Integer> result = pool.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { int sum=0 ; for(int j=0;j<=10;j++){ sum=sum+j ; } return sum; } }) ; results.add(result) ; } for(Future<Integer> result : results){ System.out.println(result.get()); } //3.關(guān)閉線程池 pool.shutdown(); }}class TaskThread implements Runnable{ private Integer num= 0 ; @Override public void run() { while(this.num<=100){ System.out.println(Thread.currentThread().getName()+" : num="+(this.num++)); } }}package cn.zzu.wcj.juc;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;/* * 一、線程池:提供了一個(gè)線程隊(duì)列,隊(duì)列中保存著所有等待狀態(tài)的線程。避免了創(chuàng)建與銷毀額外開銷,提高了響應(yīng)的速度。 * * 二、線程池的體系結(jié)構(gòu): * java.util.concurrent.Executor : 負(fù)責(zé)線程的使用與調(diào)度的根接口 * |--**ExecutorService 子接口: 線程池的主要接口 * |--ThreadPoolExecutor 線程池的實(shí)現(xiàn)類 * |--ScheduledExecutorService 子接口:負(fù)責(zé)線程的調(diào)度 * |--ScheduledThreadPoolExecutor :繼承 ThreadPoolExecutor, 實(shí)現(xiàn) ScheduledExecutorService * * 三、工具類 : Executors * ExecutorService newFixedThreadPool() : 創(chuàng)建固定大小的線程池 * ExecutorService newCachedThreadPool() : 緩存線程池,線程池的數(shù)量不固定,可以根據(jù)需求自動(dòng)的更改數(shù)量。 * ExecutorService newSingleThreadExecutor() : 創(chuàng)建單個(gè)線程池。線程池中只有一個(gè)線程 * * ScheduledExecutorService newScheduledThreadPool() : 創(chuàng)建固定大小的線程,可以延遲或定時(shí)的執(zhí)行任務(wù)。 */public class TestScheduledThreadPool { public static void main(String[] args) { ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(6) ; for(int x=0;x<8;x++){ threadPool.schedule(new Callable<Integer>() { @Override public Integer call() throws Exception { Integer result=new Random().nextInt(100) ; System.out.println(Thread.currentThread().getName()+" : result="+result); return result ; } }, 1, TimeUnit.SECONDS) ; } threadPool.shutdown(); }}9.生產(chǎn)者消費(fèi)者問題
package cn.zzu.wcj.juc;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class TestProductAndConsumerForLock { public static void main(String[] args) { Clerk clerk=new Clerk() ; Product pro=new Product(clerk) ; Consumer cons=new Consumer(clerk) ; new Thread(pro,"生產(chǎn)者A").start(); new Thread(cons,"消費(fèi)者B").start(); new Thread(pro,"生產(chǎn)者C").start(); new Thread(cons,"消費(fèi)者D").start(); }}class Clerk{ private int product=0 ; private Lock lock=new ReentrantLock() ; private Condition condition=this.lock.newCondition() ; //進(jìn)貨 public void get() throws Exception{ this.lock.lock(); try{ while(this.product>=1){ System.out.println("產(chǎn)品已滿!"); this.condition.await(); } System.out.println(Thread.currentThread().getName()+":"+(++this.product)); this.condition.signalAll(); }finally{ this.lock.unlock(); } } //賣貨 public void sale()throws Exception{ this.lock.lock(); try{ while(this.product<=0){ System.out.println("缺貨!"); this.condition.await(); } System.out.println(Thread.currentThread().getName()+":"+(--this.product)); this.condition.signalAll(); }finally{ this.lock.unlock(); } }}//生產(chǎn)者class Product implements Runnable{ private Clerk clerk ; public Product(Clerk clerk){ this.clerk=clerk ; } @Override public void run() { for (int i = 0; i < 20; i++) { try{ Thread.sleep(200); this.clerk.get(); }catch(Exception e){} } }}//消費(fèi)者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++){ try { this.clerk.sale(); } catch (Exception e) {} } }}10.線程通信
package cn.zzu.wcj.juc;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/* * 編寫一個(gè)程序,開啟 3 個(gè)線程,這三個(gè)線程的 ID 分別為 A、B、C,每個(gè)線程將自己的 ID 在屏幕上打印 10 遍,要求輸出的結(jié)果必須按順序顯示。 * 如:ABCABCABC…… 依次遞歸 */public class TestABCAlternate { public static void main(String[] args) { final AlternateDemo ad=new AlternateDemo() ; new Thread(new Runnable() { @Override public void run() { for(int i=0;i<10;i++){ try { ad.loopA(); } catch (Exception e) { e.printStackTrace(); } } } },"A").start(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<10;i++){ try { ad.loopB();; } catch (Exception e) { e.printStackTrace(); } } } },"B").start(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<10;i++){ try { ad.loopC(); } catch (Exception e) { e.printStackTrace(); } } } },"C").start(); }}class AlternateDemo{ private Integer number=1 ; //當(dāng)前正在執(zhí)行的線程的標(biāo)記 private Lock lock=new ReentrantLock() ; private Condition conditionA=lock.newCondition() ; private Condition conditionB=lock.newCondition() ; private Condition conditionC=lock.newCondition() ; public void loopA()throws Exception{ this.lock.lock(); try{ if(this.number != 1){ this.conditionA.await(); } for(int i=0;i<1;i++){ System.out.print("A"); } this.number=2 ; conditionB.signal(); }finally{ this.lock.unlock(); } } public void loopB()throws Exception{ this.lock.lock(); try{ if(this.number != 2){ this.conditionB.await(); } for(int i=0;i<1;i++){ System.out.print("B"); } this.number=3 ; conditionC.signal(); }finally{ this.lock.unlock(); } } public void loopC()throws Exception{ this.lock.lock(); try{ if(this.number != 3){ this.conditionC.await(); } for(int i=0;i<1;i++){ System.out.print("C"); } this.number=1 ; conditionA.signal(); }finally{ this.lock.unlock(); } }}11.ForkJoin框架
package cn.zzu.wcj.juc;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.ForkJoinTask;import java.util.concurrent.RecursiveTask;public class TestForkJoinPool { public static void main(String[] args) { Long start=System.currentTimeMillis() ; ForkJoinPool pool=new ForkJoinPool() ; ForkJoinTask<Long> task=new ForkJoinSumCalculate(0L,50000000L) ; Long sum=pool.invoke(task) ; System.out.println(sum); Long end=System.currentTimeMillis() ; System.out.println("框架執(zhí)行耗時(shí):"+(end-start)+"毫秒"); }}class ForkJoinSumCalculate extends RecursiveTask<Long>{ private static final long serialVersionUID = 1L; 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 x=start;x<=end;x++){ sum+=x ; } return sum ; }else{ long middle=(start+end)/2 ; ForkJoinSumCalculate left=new ForkJoinSumCalculate(start,middle) ; left.fork() ; //進(jìn)行拆分,同時(shí)壓入線程隊(duì)列 ForkJoinSumCalculate right=new ForkJoinSumCalculate(middle+1,end) ; right.fork() ; return left.join()+right.join(); } }}12.線程容器
package cn.zzu.wcj.juc;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;/* * CopyOnWriteArrayList/CopyOnWriteArraySet : “寫入并復(fù)制” * 注意:添加操作多時(shí),效率低,因?yàn)槊看翁砑訒r(shí)都會(huì)進(jìn)行復(fù)制,開銷非常的大。并發(fā)迭代操作多時(shí)可以選擇。 */public class TestCopyOnWriteArrayList { public static void main(String[] args) { HelloThread ht=new HelloThread() ; for(int i=0;i<10;i++){ new Thread(ht).start(); } }}class HelloThread implements Runnable{ //private static List<String> list=Collections.synchronizedList(new ArrayList<String>()); private static CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<String>(); static { list.add("AA") ; list.add("BB") ; list.add("CC") ; } @Override public void run() { Iterator<String> it=list.iterator() ; while(it.hasNext()){ System.out.println(it.next()); list.add("DD") ; } }}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注