如何在java中实现跨线程的通讯
生活随笔
收集整理的這篇文章主要介紹了
如何在java中实现跨线程的通讯
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一般而言,如果沒有干預的話,線程在啟動之后會一直運行到結束,但有時候我們又需要很多線程來共同完成一個任務,這就牽扯到線程間的通訊。
如何讓兩個線程先后執行?Thread.join方法
private static void demo2() {Thread A = new Thread(new Runnable() {@Overridepublic void run() {printNumber("A");}});Thread B = new Thread(new Runnable() {@Overridepublic void run() {System.out.println("B starts waiting for A");try {A.join();} catch (InterruptedException e) {e.printStackTrace();}printNumber("B");}});B.start();A.start(); }其中A.join()的意思即是等待A線程執行完畢。
如何讓兩個線程交互執行?object.wait和object.notify方法
1 /** 2 * A 1, B 1, B 2, B 3, A 2, A 3 3 */ 4 private static void demo3() { 5 Object lock = new Object(); 6 Thread A = new Thread(new Runnable() { 7 @Override 8 public void run() { 9 synchronized (lock) { 10 System.out.println("A 1"); 11 try { 12 lock.wait(); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 System.out.println("A 2"); 17 System.out.println("A 3"); 18 } 19 } 20 }); 21 Thread B = new Thread(new Runnable() { 22 @Override 23 public void run() { 24 synchronized (lock) { 25 System.out.println("B 1"); 26 System.out.println("B 2"); 27 System.out.println("B 3"); 28 lock.notify(); 29 } 30 } 31 }); 32 A.start(); 33 B.start(); 34 }A在輸出完1之后等待B的notify才會去執行其他的操作。
如何讓四個線程的其中一個等待其他三個執行完畢?CountdownLatch就是干這個的。
CountdownLatch的基本用法
如何讓三個線程的各自開始做一些事情,然后在某個時間點上進行同步?CyclicBarrier?是干這個的。
CyclicBarrier?的用法:
如何取回某個線程的返回值了?Callable?是干這個的。
先看下定義:
@FunctionalInterface public interface Callable<V> {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/V call() throws Exception; }然后直接給個例子:
1 private static void doTaskWithResultInWorker() { 2 Callable<Integer> callable = new Callable<Integer>() { 3 @Override 4 public Integer call() throws Exception { 5 System.out.println("Task starts"); 6 Thread.sleep(1000); 7 int result = 0; 8 for (int i=0; i<=100; i++) { 9 result += i; 10 } 11 System.out.println("Task finished and return result"); 12 return result; 13 } 14 }; 15 FutureTask<Integer> futureTask = new FutureTask<>(callable); 16 new Thread(futureTask).start(); 17 try { 18 System.out.println("Before futureTask.get()"); 19 System.out.println("Result:" + futureTask.get()); 20 System.out.println("After futureTask.get()"); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } catch (ExecutionException e) { 24 e.printStackTrace(); 25 } 26 }注意,其中futureTask.get()方法是阻塞調用。
?
以上都是一些很基本的應用,在新版本的CompleteFuture中其實提供了更多的鏈式操作,不過寫起來比較復雜,看起來也不清晰。
轉載于:https://www.cnblogs.com/029zz010buct/p/10440520.html
總結
以上是生活随笔為你收集整理的如何在java中实现跨线程的通讯的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 下棋安排
- 下一篇: laravel --- composer