您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Java.util.concurrent怎么用”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“Java.util.concurrent怎么用”這篇文章吧。
Java8 在線API https://blog.fondme.cn/apidoc/jdk-1.8-google/
package com.shi.juc; import java.util.concurrent.atomic.AtomicInteger; /** * * @author shiye * * 二.原子變量: jdk1.5之后,java.util.concurrent.atomic 包下提供了常用的原子變量 * 1. volatile 保證了可見性 * 2. CAS (Compare - and -swap) 算法保證數據的原子性 * CAS 算法是硬件對于并發操作共享數據的支持 * CAS 包含三個操作數: * 內存值 V * 預估值(舊值)A * 更新值 B * 當且僅當V==A 時 ,把B的值賦值給V ,否則,不做任何操作 */ public class AtomacTest { public static void main(String[] args) { AtomicThread thread = new AtomicThread(); for (int i = 0; i < 10; i++) { new Thread(thread).start(); } } } class AtomicThread implements Runnable{ public AtomicInteger auAtomicInteger = new AtomicInteger(); public int add() { return auAtomicInteger.getAndIncrement(); } @Override public void run() { System.out.println(add()); } }
package com.shi.juc; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; /** * CopyOnWriteArrayList/CopyOnWriteArraySet (寫入并復制) * 注意:添加操作多時,效率低,因為每次添加時都會進行復制,開銷非常大。 * 并發迭代讀時可以選擇使用這個,提高效率 * @author shiye * */ public class CopyOnWriteArrayListTest { public static void main(String[] args) { HelloEntity entity = new HelloEntity(); for (int i = 0; i < 10; i++) { new Thread(()-> { entity.forEachList(); },String.valueOf(i)).start(); } } } class HelloEntity{ private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList(); static { list.add("aaa"); list.add("bbb"); list.add("ccc"); } public void forEachList() { Iterator<String> iterator = list.iterator(); while(iterator.hasNext()) { System.out.println(Thread.currentThread().getName()+"線程"+iterator.next()); list.add("DDD");//再讀取的時候添加數據 } } }
package com.shi.juc; import java.util.concurrent.CountDownLatch; /** * CountDownLatch : 閉鎖 * @author shiye * */ public class TestCountDownLatch { public static void main(String[] args) throws InterruptedException { //閉鎖 final CountDownLatch latch = new CountDownLatch(10); //開始時間 long start = System.currentTimeMillis(); /** * 啟動10個線程 每個線程 循環答應1000次偶數,計算總的耗時時間 */ for (int i = 0; i < 10; i++) { new Thread( ()->{ synchronized (latch) { for (int j = 0; j <1000; j++) { if(j%10 == 0) { System.out.println(j); } } latch.countDown(); } },String.valueOf(i)).start(); } latch.await(); //結束時間 long end = System.currentTimeMillis(); System.out.println("總耗時為:"+(end - start)); } }
package com.shi.juc; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * 允許一組線程全部等待彼此達到共同屏障點的同步輔助。 * 循環阻塞在涉及固定大小的線程方的程序中很有用,這些線程必須偶爾等待彼此。 * 屏障被稱為循環 ,因為它可以在等待的線程被釋放之后重新使用。 * @author shiye * *結果: 3 集到龍珠... 0 集到龍珠... 1 集到龍珠... 4 集到龍珠... 2 集到龍珠... 5 集到龍珠... 6 集到龍珠... ********7科線程集齊,召喚神龍...... 7 集到龍珠... 8 集到龍珠... 9 集到龍珠... */ public class TestCyclicBarriar { public static void main(String[] args) { //必須集滿7個線程才能夠執行 CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()->{ System.out.println("********7科線程集齊,召喚神龍......"); }); for (int i = 0; i < 10; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"\t 集到龍珠..."); try { cyclicBarrier.await();//它必須放最下面 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } },String.valueOf(i)).start(); } } }
package com.shi.juc; import java.util.concurrent.Semaphore; /** * 模擬 6部車搶占3個車位 * @author shiye * *運行結果: Thread - 2 搶占到車位了 , 暫停3秒 Thread - 0 搶占到車位了 , 暫停3秒 Thread - 1 搶占到車位了 , 暫停3秒 Thread - 1 離開車位.... Thread - 2 離開車位.... Thread - 0 離開車位.... Thread - 3 搶占到車位了 , 暫停3秒 Thread - 5 搶占到車位了 , 暫停3秒 Thread - 4 搶占到車位了 , 暫停3秒 Thread - 4 離開車位.... Thread - 5 離開車位.... Thread - 3 離開車位.... */ public class TestSemaphore { public static void main(String[] args) { //模擬3個停車位 false:非公平 Semaphore semaphore = new Semaphore(3, false); for (int i = 0; i < 6; i++) { new Thread(()->{ try { semaphore.acquire();//搶占車位 (搶占線程) System.out.println(Thread.currentThread().getName() + " 搶占到車位了 , 暫停3秒" ); Thread.sleep(3000); System.out.println(Thread.currentThread().getName() + " 離開車位...."); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release();//釋放車位(釋放線程) } },"Thread - "+i).start(); } } }
package com.shi.juc; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * 一. 創建線程的方式三:實現Callalbe接口.相較于Runable接口方式,方法又返回值,并且可以拋出異常. * 二. 可以當成閉鎖來使用 * @author shiye * */ public class TestCallable { public static void main(String[] args) throws InterruptedException, ExecutionException { CallableDemo td = new CallableDemo(); //執行Callable方式,需要FutureTask 實現類的支持,用于接收運算結果 FutureTask<Integer> result = new FutureTask<>(td); new Thread(result).start(); //接收執行后的結果 System.out.println("---------當前線程開始了---------"); Integer sum = result.get(); //獲取當前的值時 會導致當前線程一下的全部暫停執行,直到獲取該值(慎用) System.out.println(" 和 : "+sum); System.out.println("---------當前線程終止了---------"); } } /** * * @author shiye * 創建線程并且提供返回值 */ class CallableDemo implements Callable<Integer>{ @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i < Integer.MAX_VALUE; i++) { sum+=i; } Thread.sleep(10000); return sum; } } /** * 實現Runable接口的方式實現的結果 class RunableThread implements Runnable{ @Override public void run() { } } */
package com.shi.juc; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 用于解決線程同步的問題 * Synchronized:隱士鎖 * 1. 同步代碼塊 * 2. 同步方法 * * JDK 1.5 以后 * 3.同步鎖 : Lock * 注意: 是一個顯示鎖,需要通過Lock()方法上鎖, 必須通過 unlock() 解鎖(放在finnal中最好) * * @author shiye * */ public class TestLock { static int toket = 100; public static void main(String[] args) { Lock lock = new ReentrantLock(); /** * 創建10個線程去賣票 */ for (int i = 0; i < 10; i++) { new Thread(()->{ while(toket>0) { lock.lock();//加鎖 try { if(toket>0) { Thread.sleep(200); System.out.println(Thread.currentThread().getName()+"號線程正在賣票,剩余" + (--toket)); } } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock();//解鎖 } } },String.valueOf(i)).start(); } } }
package com.shi.juc; /** * 使用隱士鎖實現的synchronized * 生產者消費者問題: * 保證生產者生產的貨能即使被消費掉(產品不存在剩余) * @author shiye * */ public class TestProductAndConsoumer { public static void main(String[] args) { Clerk clerk = new Clerk(); Productor pro = new Productor(clerk); Consumer con = new Consumer(clerk); new Thread(pro,"生產者A").start(); new Thread(con,"消費者B").start(); new Thread(pro,"生產者C").start(); new Thread(con,"消費者D").start(); } } //售貨員 class Clerk{ private int product = 0; //進貨 public synchronized void get() throws InterruptedException { while(product>=1) { System.out.println(Thread.currentThread().getName() + " :產品已滿!"); this.wait();//wait()方法必須放到循環中才行,避免虛假喚醒的問題 } System.out.println(Thread.currentThread().getName() +" 進貨: " + (++product)); this.notifyAll(); } //賣貨 public synchronized void sale() throws InterruptedException { while(product<=0) { System.out.println(Thread.currentThread().getName() + " :產品已經售罄!"); this.wait(); } 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); clerk.get(); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消費者 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 { clerk.sale(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.shi.juc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 使用顯示鎖解決:lock * 生產者消費者問題: * 保證生產者生產的貨能即使被消費掉(產品不存在剩余) * @author shiye * */ public class TestProductAndConsoumerforLock { public static void main(String[] args) { Clerk clerk = new Clerk(); Productor pro = new Productor(clerk); Consumer con = new Consumer(clerk); new Thread(pro,"生產者A").start(); new Thread(con,"消費者B").start(); new Thread(pro,"生產者C").start(); new Thread(con,"消費者D").start(); } } //售貨員 class Clerk{ private int product = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); //進貨 public void get() throws InterruptedException { try { lock.lock();//加鎖 while(product>=1) {//循環是為了,避免虛假喚醒的問題 System.out.println(Thread.currentThread().getName() + " :產品已滿!"); condition.await();//線程等待 } System.out.println(Thread.currentThread().getName() +" 進貨: " + (++product)); condition.signalAll();//線程喚醒 } finally { lock.unlock();//解鎖 } } //賣貨 public void sale() throws InterruptedException { try { lock.lock();//加鎖 while(product<=0) {//循環是為了,避免虛假喚醒的問題 System.out.println(Thread.currentThread().getName() + " :產品已經售罄!"); condition.await();//線程等待 } System.out.println(Thread.currentThread().getName()+" 賣貨: " +(--product)); condition.signalAll();//線程喚醒 } 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); clerk.get(); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消費者 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 { clerk.sale(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.shi.juc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 開啟6個線程,依次打印ABCABC... 循環打印 * @author shiye * *結果: A-1 : 打印 0 遍 B-1 : 打印 0 遍 C-2 : 打印 0 遍 A-2 : 打印 0 遍 B-2 : 打印 0 遍 C-1 : 打印 0 遍 A-1 : 打印 0 遍 B-1 : 打印 0 遍 C-2 : 打印 0 遍 A-2 : 打印 0 遍 B-2 : 打印 0 遍 C-1 : 打印 0 遍 */ public class TestABCAlert { public static void main(String[] args) { AlternateDemo demo = new AlternateDemo(); System.out.println("-----------第一輪線程-------------"); //線程A new Thread( ()->{ while(true) { demo.printA(); } },"A-1").start(); //線程B new Thread(()->{ while(true) { demo.printB(); } },"B-1").start(); //線程C new Thread(()-> { while (true) { demo.printC(); } },"C-1").start(); System.out.println("-----------第二輪線程-------------"); //線程A new Thread( ()->{ while(true) { demo.printA(); } },"A-2").start(); //線程B new Thread(()->{ while(true) { demo.printB(); } },"B-2").start(); //線程C new Thread(()-> { while (true) { demo.printC(); } },"C-2").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(); //打印A public void printA() { lock.lock();//加鎖 try { while(number != 1) { //一定要用while 不能要if 因為:存在線程線程虛假喚醒,線程搶占的問題 condition1.await();//線程 A 等待 } for (int i = 0; i < 1; i++) { System.out.println(Thread.currentThread().getName() + " : 打印 "+ i + " 遍 "); } number = 2; condition2.signal();//喚醒2線程 } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock();//解鎖 } } //打印B public void printB() { lock.lock();//上鎖 try { while(number != 2) {//一定要用while 不能要if 因為:存在線程線程虛假喚醒,線程搶占的問題 condition2.await(); } for (int i = 0; i < 1; i++) { System.out.println(Thread.currentThread().getName() + " : 打印 "+ i + " 遍 "); } number = 3; condition3.signal();//喚醒3線程 } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock();//解鎖 } } //打印C public void printC() { lock.lock();//上鎖 try { while(number != 3) {//一定要用while 不能要if 因為:存在線程線程虛假喚醒,線程搶占的問題 condition3.await(); } for (int i = 0; i < 1; i++) { System.out.println(Thread.currentThread().getName() + " : 打印 "+ i + " 遍 "); } number = 1; condition1.signal();//喚醒1線程 } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock();//解鎖 } } }
package com.shi.juc; import java.time.LocalTime; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 讀寫鎖 * 寫寫/讀寫 需要互斥 * 讀讀 不需要互斥 * @author shiye * * 結果: 完全證明上面的理論成功 read-0 正在讀 0 當前時間:14:47:47.534 read-1 正在讀 0 當前時間:14:47:47.534 write-0 寫過之后的值為: 111 當前時間:14:47:52.535 write-1 寫過之后的值為: 111 當前時間:14:47:57.536 write-2 寫過之后的值為: 111 當前時間:14:48:02.536 read-2 正在讀 111 當前時間:14:48:07.537 read-3 正在讀 111 當前時間:14:48:07.537 write-3 寫過之后的值為: 111 當前時間:14:48:12.537 write-5 寫過之后的值為: 111 當前時間:14:48:17.537 * */ public class TestReadAndWrite { public static void main(String[] args) { ReadAndWrite item = new ReadAndWrite(); //啟動100個讀寫線程操作數據 for (int i = 0; i < 10; i++) { //讀線程 new Thread(()->{ item.read(); },"read-" + i ).start(); //寫線程 new Thread(()->{ item.write(); },"write-" + i ).start(); } } } class ReadAndWrite{ private int number = 0; private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();//讀寫鎖 //讀 public void read() { readWriteLock.readLock().lock();//上讀鎖 try { Thread.sleep(5000);//睡眠5秒鐘 System.out.println(Thread.currentThread().getName() + " 正在讀 " + number + " 當前時間:"+ LocalTime.now()); } catch (InterruptedException e) { e.printStackTrace(); }finally { readWriteLock.readLock().unlock();//釋放讀鎖 } } //寫 public void write() { readWriteLock.writeLock().lock(); try { number = 111; Thread.sleep(5000);//寫需要花費5s鐘時間 System.out.println(Thread.currentThread().getName() + " 寫過之后的值為: " + number+ " 當前時間:"+ LocalTime.now()); } catch (Exception e) { e.printStackTrace(); }finally { readWriteLock.writeLock().unlock(); } } }
package com.shi.juc; /** * 線程8鎖 * @author shiye * * 1. 倆個普通同步方法,倆個線程,標準打印,打印?// one two * 2. 新增Thread.sleep() 給 getOne() , 打印?// one two * 3. 新增普通getThree(), 打印? // Three one two * 4. 倆個普通同步方法, 倆個Number對象 打印?// two one * 5. 修改getOne() 為靜態同步方法, 一個Number對象?//two one * 6. 修改倆個方法均為 靜態同步方法,一個Number對像?//one two * 7. 一個靜態同步方法,一個非靜態同步方法,倆個Number?//two one * 8. 倆個靜態同步方法,倆個Number對象 ? //one two * * 線程八鎖的關鍵: * 一. 非靜態方法鎖的默認為this,靜態方法的鎖為對應的Class實力 * 二. 某一個時刻內,只能有一個線程持有鎖,無論幾個方法。 * */ public class TestThread8Lock { public static void main(String[] args) { Number number = new Number(); Number number2 = new Number(); //線程1 new Thread(()->{ number.getOne(); }).start(); //線程2 new Thread(()->{ // number.getTwo(); number2.getTwo(); }).start(); //線程3 // new Thread(()->{ // number.getThree(); // }).start(); } } class Number{ public static synchronized void getOne() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("one"); } public static synchronized void getTwo() { System.out.println("two"); } // public void getThree() { // System.out.println("Three"); // } }
package com.shi.juc; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * 一、線程池:提供了一個線程隊列,隊列中保存著所有等待狀態的線程。避免了創建與銷毀額外開銷,提高了響應的速度。 * * 二、線程池的體系結構: * java.util.concurrent.Executor : 負責線程的使用與調度的根接口 * |--**ExecutorService 子接口: 線程池的主要接口 * |--ThreadPoolExecutor 線程池的實現類 * |--ScheduledExecutorService 子接口:負責線程的調度 * |--ScheduledThreadPoolExecutor :繼承 ThreadPoolExecutor, 實現 ScheduledExecutorService * * 三、工具類 : Executors * ExecutorService newFixedThreadPool() : 創建固定大小的線程池 * ExecutorService newCachedThreadPool() : 緩存線程池,線程池的數量不固定,可以根據需求自動的更改數量。 * ExecutorService newSingleThreadExecutor() : 創建單個線程池。線程池中只有一個線程 * * ScheduledExecutorService newScheduledThreadPool() : 創建固定大小的線程,可以延遲或定時的執行任務。 * @author shiye * */ public class TestThreadPool { public static void main(String[] args) throws InterruptedException, ExecutionException { Number1 number1 = new Number1(); //1 創建長度5個線程的線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2 創建10個線程 執行線程 //結果: 每個線程都要按順序 一個一個執行,而且必須要一個線程把值返回了才執行下一個線程(閉鎖) for (int i = 0; i < 10; i++) { Future<Integer> future = pool.submit(()->{ int sum = number1.sum(); return sum; }); Integer sum = future.get(); System.out.println(Thread.currentThread().getName()+ " 線程 執行的結果為: " + sum); } //3 創建10個線程 執行線程 //結果 ,每個線程分開操作不需要過多的等待, for (int i = 0; i < 10; i++) { pool.submit(()->{ number1.sum(); }); } pool.shutdown();//一定要關閉線程池 } } /** * 計算 1—100 的和 ,每次計算睡眠1s * @author shiye * */ class Number1{ public int sum() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } int sum = 0; for (int i = 0; i < 101; i++) { sum +=i; } System.out.println(Thread.currentThread().getName()+ " 線程 執行的結果為: " + sum); return sum; } }
package com.shi.juc; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * ScheduledExecutorService newScheduledThreadPool() : 創建固定大小的線程,可以延遲或定時的執行任務。 * @author shiye * */ public class TestScheduledThreadPool { public static void main(String[] args) throws InterruptedException, ExecutionException { //1 創建一個帶任務調度的線程池 ScheduledExecutorService pool = Executors.newScheduledThreadPool(5); for (int i = 0; i < 10; i++) { //啟動一個任務調度 ScheduledFuture<?> future = pool.schedule(()->{ int num = new Random().nextInt(100); System.out.println(Thread.currentThread().getName() + " 線程 產生的隨機數為: " + num); return num; },3,TimeUnit.SECONDS);// 延遲3s創建一個線程 System.out.println(future.get()); } pool.shutdown();//關閉線程池 } }
以上是“Java.util.concurrent怎么用”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。