如果您知道进程间如何通信,那么您将很容易理解线程之间通信,在开发两个或多个线程交换某些信息的应用程序时,线程间通信非常重要。
有三种简单的方法和一些使线程通信成为可能的小技巧。这三种方法都在下面列出-
| Sr.No. | Method & Remark |
|---|---|
| 1 |
public void wait() 使当前线程等待,直到另一个线程调用notify()。 |
| 2 |
public void notify() 唤醒正在此对象的监视器上等待的单个线程。 |
| 3 |
public void notifyAll() 唤醒同一对象上所有调用wait()的线程。 |
这些方法已在对象(Object)中作为 final 方法实现,因此在所有类中都可用。
此示例显示了两个线程如何使用 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();
}
}
</span><span class="typ">System</span><span class="pun">.</span><span class="kwd">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="pln">msg</span><span class="pun">);</span><span class="pln">
flag </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln">
notify</span><span class="pun">();</span><span class="pln">
}
}
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!