
- Java 併發教程
- 併發 - 首頁
- 併發 - 概述
- 併發 - 環境設定
- 併發 - 主要操作
- 執行緒間通訊
- 併發 - 同步
- 併發 - 死鎖
- 工具類示例
- 併發 - ThreadLocal
- 併發 - ThreadLocalRandom
- 鎖示例
- 併發 - 鎖 (Lock)
- 併發 - 讀寫鎖 (ReadWriteLock)
- 併發 - 條件 (Condition)
- 原子變數示例
- 併發 - AtomicInteger
- 併發 - AtomicLong
- 併發 - AtomicBoolean
- 併發 - AtomicReference
- 併發 - AtomicIntegerArray
- 併發 - AtomicLongArray
- 併發 - AtomicReferenceArray
- 執行器示例
- 併發 - 執行器 (Executor)
- 併發 - 執行器服務 (ExecutorService)
- ScheduledExecutorService
- 執行緒池示例
- 併發 - newFixedThreadPool
- 併發 - newCachedThreadPool
- newScheduledThreadPool
- newSingleThreadExecutor
- 併發 - ThreadPoolExecutor
- ScheduledThreadPoolExecutor
- 高階示例
- 併發 - Futures 和 Callables
- 併發 - Fork-Join 框架
- 併發集合
- 併發 - BlockingQueue
- 併發 - ConcurrentMap
- ConcurrentNavigableMap
- 併發 - 有用資源
- 併發 - 快速指南
- 併發 - 有用資源
- 併發 - 討論
執行緒間通訊
如果您瞭解程序間通訊,那麼理解執行緒間通訊就很容易了。當您開發一個兩個或多個執行緒交換資訊的應用程式時,執行緒間通訊非常重要。
有三種簡單的方法和一個小技巧可以實現執行緒通訊。所有三種方法都列在下面:
序號 | 方法及描述 |
---|---|
1 | public void wait() 導致當前執行緒等待,直到另一個執行緒呼叫 notify()。 |
2 | public void notify() 喚醒正在等待此物件監視器的單個執行緒。 |
3 | public void notifyAll() 喚醒所有在同一個物件上呼叫 wait() 的執行緒。 |
這些方法已在 Object 中實現為 **final** 方法,因此它們在所有類中都可用。所有三個方法只能在 **synchronized** 上下文中呼叫。
示例
此示例演示了兩個執行緒如何使用 **wait()** 和 **notify()** 方法進行通訊。您可以使用相同的概念建立複雜的系統。
class Chat { boolean flag = false; public synchronized void Question(String msg) { if (flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = true; notify(); } public synchronized void Answer(String msg) { if (!flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = false; notify(); } } class T1 implements Runnable { Chat m; String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" }; public T1(Chat m1) { this.m = m1; new Thread(this, "Question").start(); } public void run() { for (int i = 0; i < s1.length; i++) { m.Question(s1[i]); } } } class T2 implements Runnable { Chat m; String[] s2 = { "Hi", "I am good, what about you?", "Great!" }; public T2(Chat m2) { this.m = m2; new Thread(this, "Answer").start(); } public void run() { for (int i = 0; i < s2.length; i++) { m.Answer(s2[i]); } } } public class TestThread { public static void main(String[] args) { Chat m = new Chat(); new T1(m); new T2(m); } }
編譯並執行上述程式後,會產生以下結果:
輸出
Hi Hi How are you ? I am good, what about you? I am also doing fine! Great!
以上示例取自並修改自 [https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]
廣告