當前位置:
首頁 >
Java5的 线程并发库
發布時間:2025/5/22
27
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Java5的 线程并发库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java.util.concurrent.atomic
一個小型工具包,支持單個變量上的無鎖線程安全編程.
包含的類:
這些類的相關操作都是原子性的
java.util.concurrent
線程池
//線程池的創建 //創建一個線程池,該線程池重用固定數量的從共享無界隊列中運行的線程。 //在任何時候,最多nThreads個線程同時處理任務。 //如果所有線程處于活動狀態時又提交其他任務,則它們將在等待隊列中直到有一個線程空閑可用。 //如果任何線程由于在關閉之前的執行期間發生故障而終止,如果需要執行后續任務,則新線程將占用它。 //池中的線程將一直存在,直到調用shutdown方法 。 //public static ExecutorService newFixedThreadPool(int nThreads) ExecutorService es = Executors.newFixedThreadPool(3);//向線程池中添加任務 es.execute(new Runnable(){});//可以添加多個任務 //但是最多有三個線程去執行這些任務,即最多只有三個任務同時執行//線程池的關閉 es.shutdown();//所有任務執行完后關閉 es.shutdownNow(); //立即關閉,不管任務有沒有執行完//創建緩存的線程池 //創建一個根據需要創建新線程的線程池,但在可用時將重新使用以前構造的線程。 //這些池通常會提高執行許多短暫異步任務的程序的性能。 //調用execute將重用以前構造的線程(如果可用)。 //如果沒有可用的線程,將創建一個新的線程并將其添加到該池中。 //未使達六十秒的線程將被終止并從緩存中刪除。 //因此,長時間保持閑置的池將不會消耗任何資源 public static ExecutorService newCachedThreadPool()//創建只有單個線程的線程池public static ExecutorService newSingleThreadExecutor() //如何實現線程死掉后重新啟動,通過單一線程池,這樣這個線程死掉后,線程池會自動重新創建一個線程來替代//調度線程池 ScheduledExecutorService se = Executors.newScheduledThreadPool(3); se.schedule(new Runnable() //3秒后執行 { @Overridepublic void run(){System.out.println("bombing");} }, 3, TimeUnit.SECONDS);se.scheduleAtFixedRate(new Runnable()//6秒后第一次執行,以后每隔兩秒執行一次 {@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來執行任務,Future獲取結果,在使用到結果的時候如果Callable還沒結束,程序會暫停并等待結果,就跟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("等待結果");try{System.out.println("返回結果:"+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進行線程間的通信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();}}}轉載于:https://www.cnblogs.com/phasd/p/9245019.html
總結
以上是生活随笔為你收集整理的Java5的 线程并发库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#操作Sqlite快速入门及相关工具收
- 下一篇: 从零开始实现一个简易的Java MVC框