這篇文章主要為大家展示了“Java.util.concurrent怎么用”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Java.util.concurrent怎么用”這篇文章吧。
我們提供的服務(wù)有:成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、溆浦ssl等。為上千多家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的溆浦網(wǎng)站制作公司
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) 算法保證數(shù)據(jù)的原子性 * CAS 算法是硬件對(duì)于并發(fā)操作共享數(shù)據(jù)的支持 * CAS 包含三個(gè)操作數(shù): * 內(nèi)存值 V * 預(yù)估值(舊值)A * 更新值 B * 當(dāng)且僅當(dāng)V==A 時(shí) ,把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 (寫入并復(fù)制) * 注意:添加操作多時(shí),效率低,因?yàn)槊看翁砑訒r(shí)都會(huì)進(jìn)行復(fù)制,開銷非常大。 * 并發(fā)迭代讀時(shí)可以選擇使用這個(gè),提高效率 * @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");//再讀取的時(shí)候添加數(shù)據(jù) } } }
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); //開始時(shí)間 long start = System.currentTimeMillis(); /** * 啟動(dòng)10個(gè)線程 每個(gè)線程 循環(huán)答應(yīng)1000次偶數(shù),計(jì)算總的耗時(shí)時(shí)間 */ 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(); //結(jié)束時(shí)間 long end = System.currentTimeMillis(); System.out.println("總耗時(shí)為:"+(end - start)); } }
package com.shi.juc; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * 允許一組線程全部等待彼此達(dá)到共同屏障點(diǎn)的同步輔助。 * 循環(huán)阻塞在涉及固定大小的線程方的程序中很有用,這些線程必須偶爾等待彼此。 * 屏障被稱為循環(huán) ,因?yàn)樗梢栽诘却木€程被釋放之后重新使用。 * @author shiye * *結(jié)果: 3 集到龍珠... 0 集到龍珠... 1 集到龍珠... 4 集到龍珠... 2 集到龍珠... 5 集到龍珠... 6 集到龍珠... ********7科線程集齊,召喚神龍...... 7 集到龍珠... 8 集到龍珠... 9 集到龍珠... */ public class TestCyclicBarriar { public static void main(String[] args) { //必須集滿7個(gè)線程才能夠執(zhí)行 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個(gè)車位 * @author shiye * *運(yùn)行結(jié)果: 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個(gè)停車位 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; /** * 一. 創(chuàng)建線程的方式三:實(shí)現(xiàn)Callalbe接口.相較于Runable接口方式,方法又返回值,并且可以拋出異常. * 二. 可以當(dāng)成閉鎖來使用 * @author shiye * */ public class TestCallable { public static void main(String[] args) throws InterruptedException, ExecutionException { CallableDemo td = new CallableDemo(); //執(zhí)行Callable方式,需要FutureTask 實(shí)現(xiàn)類的支持,用于接收運(yùn)算結(jié)果 FutureTask<Integer> result = new FutureTask<>(td); new Thread(result).start(); //接收?qǐng)?zhí)行后的結(jié)果 System.out.println("---------當(dāng)前線程開始了---------"); Integer sum = result.get(); //獲取當(dāng)前的值時(shí) 會(huì)導(dǎo)致當(dāng)前線程一下的全部暫停執(zhí)行,直到獲取該值(慎用) System.out.println(" 和 : "+sum); System.out.println("---------當(dāng)前線程終止了---------"); } } /** * * @author shiye * 創(chuàng)建線程并且提供返回值 */ 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; } } /** * 實(shí)現(xiàn)Runable接口的方式實(shí)現(xiàn)的結(jié)果 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 * 注意: 是一個(gè)顯示鎖,需要通過Lock()方法上鎖, 必須通過 unlock() 解鎖(放在finnal中最好) * * @author shiye * */ public class TestLock { static int toket = 100; public static void main(String[] args) { Lock lock = new ReentrantLock(); /** * 創(chuàng)建10個(gè)線程去賣票 */ 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()+"號(hào)線程正在賣票,剩余" + (--toket)); } } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock();//解鎖 } } },String.valueOf(i)).start(); } } }
package com.shi.juc; /** * 使用隱士鎖實(shí)現(xiàn)的synchronized * 生產(chǎn)者消費(fèi)者問題: * 保證生產(chǎn)者生產(chǎn)的貨能即使被消費(fèi)掉(產(chǎn)品不存在剩余) * @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,"生產(chǎn)者A").start(); new Thread(con,"消費(fèi)者B").start(); new Thread(pro,"生產(chǎn)者C").start(); new Thread(con,"消費(fèi)者D").start(); } } //售貨員 class Clerk{ private int product = 0; //進(jìn)貨 public synchronized void get() throws InterruptedException { while(product>=1) { System.out.println(Thread.currentThread().getName() + " :產(chǎn)品已滿!"); this.wait();//wait()方法必須放到循環(huán)中才行,避免虛假喚醒的問題 } System.out.println(Thread.currentThread().getName() +" 進(jìn)貨: " + (++product)); this.notifyAll(); } //賣貨 public synchronized void sale() throws InterruptedException { while(product<=0) { System.out.println(Thread.currentThread().getName() + " :產(chǎn)品已經(jīng)售罄!"); this.wait(); } System.out.println(Thread.currentThread().getName()+" 賣貨: " +(--product)); this.notifyAll(); } } //生產(chǎn)者 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(); } } } } //消費(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 { 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 * 生產(chǎn)者消費(fèi)者問題: * 保證生產(chǎn)者生產(chǎn)的貨能即使被消費(fèi)掉(產(chǎn)品不存在剩余) * @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,"生產(chǎn)者A").start(); new Thread(con,"消費(fèi)者B").start(); new Thread(pro,"生產(chǎn)者C").start(); new Thread(con,"消費(fèi)者D").start(); } } //售貨員 class Clerk{ private int product = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); //進(jìn)貨 public void get() throws InterruptedException { try { lock.lock();//加鎖 while(product>=1) {//循環(huán)是為了,避免虛假喚醒的問題 System.out.println(Thread.currentThread().getName() + " :產(chǎn)品已滿!"); condition.await();//線程等待 } System.out.println(Thread.currentThread().getName() +" 進(jìn)貨: " + (++product)); condition.signalAll();//線程喚醒 } finally { lock.unlock();//解鎖 } } //賣貨 public void sale() throws InterruptedException { try { lock.lock();//加鎖 while(product<=0) {//循環(huán)是為了,避免虛假喚醒的問題 System.out.println(Thread.currentThread().getName() + " :產(chǎn)品已經(jīng)售罄!"); condition.await();//線程等待 } System.out.println(Thread.currentThread().getName()+" 賣貨: " +(--product)); condition.signalAll();//線程喚醒 } finally { lock.unlock();//解鎖 } } } //生產(chǎn)者 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(); } } } } //消費(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 { 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個(gè)線程,依次打印ABCABC... 循環(huán)打印 * @author shiye * *結(jié)果: 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;//當(dāng)前線程執(zhí)行線程的標(biāo)記 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 因?yàn)椋捍嬖诰€程線程虛假喚醒,線程搶占的問題 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 因?yàn)椋捍嬖诰€程線程虛假喚醒,線程搶占的問題 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 因?yàn)椋捍嬖诰€程線程虛假喚醒,線程搶占的問題 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 * * 結(jié)果: 完全證明上面的理論成功 read-0 正在讀 0 當(dāng)前時(shí)間:14:47:47.534 read-1 正在讀 0 當(dāng)前時(shí)間:14:47:47.534 write-0 寫過之后的值為: 111 當(dāng)前時(shí)間:14:47:52.535 write-1 寫過之后的值為: 111 當(dāng)前時(shí)間:14:47:57.536 write-2 寫過之后的值為: 111 當(dāng)前時(shí)間:14:48:02.536 read-2 正在讀 111 當(dāng)前時(shí)間:14:48:07.537 read-3 正在讀 111 當(dāng)前時(shí)間:14:48:07.537 write-3 寫過之后的值為: 111 當(dāng)前時(shí)間:14:48:12.537 write-5 寫過之后的值為: 111 當(dāng)前時(shí)間:14:48:17.537 * */ public class TestReadAndWrite { public static void main(String[] args) { ReadAndWrite item = new ReadAndWrite(); //啟動(dòng)100個(gè)讀寫線程操作數(shù)據(jù) 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 + " 當(dāng)前時(shí)間:"+ LocalTime.now()); } catch (InterruptedException e) { e.printStackTrace(); }finally { readWriteLock.readLock().unlock();//釋放讀鎖 } } //寫 public void write() { readWriteLock.writeLock().lock(); try { number = 111; Thread.sleep(5000);//寫需要花費(fèi)5s鐘時(shí)間 System.out.println(Thread.currentThread().getName() + " 寫過之后的值為: " + number+ " 當(dāng)前時(shí)間:"+ LocalTime.now()); } catch (Exception e) { e.printStackTrace(); }finally { readWriteLock.writeLock().unlock(); } } }
package com.shi.juc; /** * 線程8鎖 * @author shiye * * 1. 倆個(gè)普通同步方法,倆個(gè)線程,標(biāo)準(zhǔn)打印,打???// one two * 2. 新增Thread.sleep() 給 getOne() , 打印?// one two * 3. 新增普通getThree(), 打??? // Three one two * 4. 倆個(gè)普通同步方法, 倆個(gè)Number對(duì)象 打印?// two one * 5. 修改getOne() 為靜態(tài)同步方法, 一個(gè)Number對(duì)象?//two one * 6. 修改倆個(gè)方法均為 靜態(tài)同步方法,一個(gè)Number對(duì)像?//one two * 7. 一個(gè)靜態(tài)同步方法,一個(gè)非靜態(tài)同步方法,倆個(gè)Number?//two one * 8. 倆個(gè)靜態(tài)同步方法,倆個(gè)Number對(duì)象 ? //one two * * 線程八鎖的關(guān)鍵: * 一. 非靜態(tài)方法鎖的默認(rèn)為this,靜態(tài)方法的鎖為對(duì)應(yīng)的Class實(shí)力 * 二. 某一個(gè)時(shí)刻內(nèi),只能有一個(gè)線程持有鎖,無論幾個(gè)方法。 * */ 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; /** * 一、線程池:提供了一個(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ù)。 * @author shiye * */ public class TestThreadPool { public static void main(String[] args) throws InterruptedException, ExecutionException { Number1 number1 = new Number1(); //1 創(chuàng)建長(zhǎng)度5個(gè)線程的線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2 創(chuàng)建10個(gè)線程 執(zhí)行線程 //結(jié)果: 每個(gè)線程都要按順序 一個(gè)一個(gè)執(zhí)行,而且必須要一個(gè)線程把值返回了才執(zhí)行下一個(gè)線程(閉鎖) 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()+ " 線程 執(zhí)行的結(jié)果為: " + sum); } //3 創(chuàng)建10個(gè)線程 執(zhí)行線程 //結(jié)果 ,每個(gè)線程分開操作不需要過多的等待, for (int i = 0; i < 10; i++) { pool.submit(()->{ number1.sum(); }); } pool.shutdown();//一定要關(guān)閉線程池 } } /** * 計(jì)算 1—100 的和 ,每次計(jì)算睡眠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()+ " 線程 執(zhí)行的結(jié)果為: " + 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() : 創(chuàng)建固定大小的線程,可以延遲或定時(shí)的執(zhí)行任務(wù)。 * @author shiye * */ public class TestScheduledThreadPool { public static void main(String[] args) throws InterruptedException, ExecutionException { //1 創(chuàng)建一個(gè)帶任務(wù)調(diào)度的線程池 ScheduledExecutorService pool = Executors.newScheduledThreadPool(5); for (int i = 0; i < 10; i++) { //啟動(dòng)一個(gè)任務(wù)調(diào)度 ScheduledFuture<?> future = pool.schedule(()->{ int num = new Random().nextInt(100); System.out.println(Thread.currentThread().getName() + " 線程 產(chǎn)生的隨機(jī)數(shù)為: " + num); return num; },3,TimeUnit.SECONDS);// 延遲3s創(chuàng)建一個(gè)線程 System.out.println(future.get()); } pool.shutdown();//關(guān)閉線程池 } }
以上是“Java.util.concurrent怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享文章:Java.util.concurrent怎么用
分享路徑:http://jinyejixie.com/article36/gpegsg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、App設(shè)計(jì)、品牌網(wǎng)站制作、網(wǎng)站內(nèi)鏈、ChatGPT、移動(dòng)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)