public void wait()导致当前线程等待,直到另一个线程调用notify()。
public void notify()唤醒正在此对象监视器上等待的单个线程。
public void notifyAll()唤醒在同一对象上调用wait()的所有线程。
1.启动线程
public class OneActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cabinet_type_1);
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
2.启动两个线程 执行不同的任务
public class Chat {
boolean flag = false;
//被synchronized 修饰的方法 同一时间只能被一个线程使用
public synchronized void Question(String msg) {
if (flag) {
try {
wait(); //线程等待,直到另一个线程调用notify()
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.e("TAG", msg);
flag = true;
notify(); //唤醒正在此对象监视器上等待的单个线程
}
public synchronized void Answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.e("TAG", msg);
flag = false;
notify();
}
}
3.线程1:
public class T1 implements Runnable {
Chat m;
String[] s1 = {"Thread1-Hi", "Thread1-How are you ?", "Thread1-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]);
}
}
}
4.线程2:
public class T2 implements Runnable {
Chat m;
String[] s2 = {"Thread2-Hi", "Thread2-I am good, what about you?", "Thread2-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]);
}
}
}
运行结果:
05-16 18:28:59.705 19418-19438/? E/TAG: Thread1-Hi
05-16 18:28:59.705 19418-19439/? E/TAG: Thread2-Hi
05-16 18:28:59.705 19418-19438/? E/TAG: Thread1-How are you ?
05-16 18:28:59.705 19418-19439/? E/TAG: Thread2-I am good, what about you?
05-16 18:28:59.705 19418-19438/? E/TAG: Thread1-I am also doing fine!
05-16 18:28:59.705 19418-19439/? E/TAG: Thread2-Great!