简介:java既然作为支持多线程编程语言,当你开发两个或多个线程交换一些信息的应用程序时,线程间的通信还是很重要的。在这里使用wait()和notify()/notifyAll()方法以及syncrhoized关键字实现一个简单的线程间对话通信。您可以使用相同的概念来创建一个复杂的系统。
注意事项:
不了解wait()和notify()/notifyAll()方法看我上篇文章-点击
为什么使用syncrhoized关键字-点击
实例:
public class Chat {
//是否唤醒等待标识
boolean flag = false;
public synchronized void Question(String msg){
if(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
//System.out.println("提问前:"+flag);
flag = true;
//System.out.println("提问后:"+flag);
notify();
}
public synchronized void Answer(String msg){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
//System.out.println("回答前:"+flag);
flag = false;
//System.out.println("回答后:"+flag);
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();
}
@Override
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();
}
@Override
public void run() {
for (int i = 0; i < s2.length; i++) {
m.Answer(s2[i]);
}
}
}
package Threads;
public class TestThread {
public static void main(String[] args) {
//线程的基本通信
Chat chat = new Chat();
new T1(chat);
new T2(chat);
}
}
结果: