Java - 线程间通信
如果你了解进程间通信,那么理解线程间通信就会很容易。
Java 中的线程间通信
当你开发一个应用,其中两个或多个线程需要交换信息时,线程间通信就变得很重要。线程间通信通过 Object class 的 wait()、notify() 和 notifyAll() 方法来实现。
用于线程间通信的方法
有三个简单的方法和一个小技巧可以实现线程通信。这三个方法列在下面 −
| Sr.No. | Method & Description |
|---|---|
| 1 | public void wait() 使当前线程等待,直到另一个线程调用 notify()。 |
| 2 | public void notify() 唤醒等待此对象监视器的单个线程。 |
| 3 | public void notifyAll() 唤醒所有在同一对象上调用 wait() 的线程。 |
这些方法在 Object 中被实现为 final 方法,因此它们在所有类中都可用。这三个方法只能在 synchronized 上下文中调用。
Java 中线程间通信的示例
这个示例展示了如何使用 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);
}
}
当上面的程序被编译并执行时,会产生以下结果 −
Output
Hi Hi How are you ? I am good, what about you? I am also doing fine! Great!