Java5的 线程并发库
生活随笔
收集整理的這篇文章主要介紹了
Java5的 线程并发库
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
java.util.concurrent.atomic
一個(gè)小型工具包,支持單個(gè)變量上的無鎖線程安全編程.
包含的類:
這些類的相關(guān)操作都是原子性的
java.util.concurrent
線程池
//線程池的創(chuàng)建 //創(chuàng)建一個(gè)線程池,該線程池重用固定數(shù)量的從共享無界隊(duì)列中運(yùn)行的線程。 //在任何時(shí)候,最多nThreads個(gè)線程同時(shí)處理任務(wù)。 //如果所有線程處于活動(dòng)狀態(tài)時(shí)又提交其他任務(wù),則它們將在等待隊(duì)列中直到有一個(gè)線程空閑可用。 //如果任何線程由于在關(guān)閉之前的執(zhí)行期間發(fā)生故障而終止,如果需要執(zhí)行后續(xù)任務(wù),則新線程將占用它。 //池中的線程將一直存在,直到調(diào)用shutdown方法 。 //public static ExecutorService newFixedThreadPool(int nThreads) ExecutorService es = Executors.newFixedThreadPool(3);//向線程池中添加任務(wù) es.execute(new Runnable(){});//可以添加多個(gè)任務(wù) //但是最多有三個(gè)線程去執(zhí)行這些任務(wù),即最多只有三個(gè)任務(wù)同時(shí)執(zhí)行//線程池的關(guān)閉 es.shutdown();//所有任務(wù)執(zhí)行完后關(guān)閉 es.shutdownNow(); //立即關(guān)閉,不管任務(wù)有沒有執(zhí)行完//創(chuàng)建緩存的線程池 //創(chuàng)建一個(gè)根據(jù)需要?jiǎng)?chuàng)建新線程的線程池,但在可用時(shí)將重新使用以前構(gòu)造的線程。 //這些池通常會(huì)提高執(zhí)行許多短暫異步任務(wù)的程序的性能。 //調(diào)用execute將重用以前構(gòu)造的線程(如果可用)。 //如果沒有可用的線程,將創(chuàng)建一個(gè)新的線程并將其添加到該池中。 //未使達(dá)六十秒的線程將被終止并從緩存中刪除。 //因此,長時(shí)間保持閑置的池將不會(huì)消耗任何資源 public static ExecutorService newCachedThreadPool()//創(chuàng)建只有單個(gè)線程的線程池public static ExecutorService newSingleThreadExecutor() //如何實(shí)現(xiàn)線程死掉后重新啟動(dòng),通過單一線程池,這樣這個(gè)線程死掉后,線程池會(huì)自動(dòng)重新創(chuàng)建一個(gè)線程來替代//調(diào)度線程池 ScheduledExecutorService se = Executors.newScheduledThreadPool(3); se.schedule(new Runnable() //3秒后執(zhí)行 { @Overridepublic void run(){System.out.println("bombing");} }, 3, TimeUnit.SECONDS);se.scheduleAtFixedRate(new Runnable()//6秒后第一次執(zhí)行,以后每隔兩秒執(zhí)行一次 {@Overridepublic void run(){System.out.println("bombing");} }, 6, 2, TimeUnit.SECONDS);se.scheduleWithFixedDelay(new Runnable() {@Overridepublic void run(){System.out.println("bombing");} }, 3, 2, TimeUnit.SECONDS);Callable 與 Future 類似 dot net 的async與await
使用Callable來執(zhí)行任務(wù),Future獲取結(jié)果,在使用到結(jié)果的時(shí)候如果Callable還沒結(jié)束,程序會(huì)暫停并等待結(jié)果,就跟await一樣
public class CallableAndFuture { /*** @param args*/ public static void main(String[] args) {ExecutorService es = Executors.newSingleThreadExecutor();Future<String> future = es.submit(new Callable<String>(){@Overridepublic String call() throws Exception{Thread.sleep(2000);return "Hello";}});System.out.println("等待結(jié)果");try{System.out.println("返回結(jié)果:"+future.get());}catch (InterruptedException e){e.printStackTrace();}catch (ExecutionException e){e.printStackTrace();}es.shutdown();ExecutorService es1 = Executors.newFixedThreadPool(10);CompletionService<Integer> completionService = new ExecutorCompletionService<>(es1);for(int i=1;i<=10;i++){final int sequence=i;completionService.submit(new Callable<Integer>(){@Overridepublic Integer call() throws Exception{Thread.sleep(new Random().nextInt(5000));return sequence;}});}for(int i=0;i<10;i++){try{System.out.println(completionService.take().get());}catch (InterruptedException | ExecutionException e){e.printStackTrace();}}es1.shutdown(); } }java.util.concurrent.locks
主要的類與接口
Condition 線程通信
//利用condition進(jìn)行線程間的通信static class Business{private ReentrantLock lock = new ReentrantLock();private Condition condition1 = lock.newCondition();private Condition condition2 = lock.newCondition();private Condition condition3 = lock.newCondition();private int flag=1;public void sub(int i){lock.lock();try{while(flag!=1){try{//this.wait();condition1.await();}catch (InterruptedException e){e.printStackTrace();}}for (int j = 1; j <= 10; j++){System.out.println("sub thread sequence of " + j+",loop of "+i);}flag=2;condition2.signal();}finally{// TODO: handle finally clauselock.unlock();}}public void sub2(int i){lock.lock();try{while(flag!=2){try{//this.wait();condition2.await();}catch (InterruptedException e){e.printStackTrace();}}for (int j = 1; j <= 20; j++){System.out.println("sub2 thread sequence of " + j+",loop of "+i);}flag=3;condition3.signal();}finally{// TODO: handle finally clauselock.unlock();}}public void main(int i){lock.lock();try{while(flag!=3){try{//this.wait();condition3.await();}catch (InterruptedException e){e.printStackTrace();}}for (int j = 1; j <= 100; j++){System.out.println("main thread sequence of " + j+",loop of "+i);}flag=1;//this.notify();condition1.signal();}finally{// TODO: handle finally clauselock.unlock();}}}轉(zhuǎn)載于:https://www.cnblogs.com/phasd/p/9245019.html
總結(jié)
以上是生活随笔為你收集整理的Java5的 线程并发库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#操作Sqlite快速入门及相关工具收
- 下一篇: 从零开始实现一个简易的Java MVC框