如果你知道进程间通信,那么就很容易理解线程间通信。 当您开发两个或多个线程交换一些信息的应用程序时,线程间通信很重要。
有三个简单的方法和一个小技巧,使线程通信成为可能。 所有三种方法都列在下面 -
编号 | 方法 | 描述 |
---|---|---|
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();
}
}
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!