【发布时间】:2015-01-26 17:39:24
【问题描述】:
我是同步新手,并试图了解等待和通知的工作原理。
问题:-
程序同时执行 2 个线程 - T1 和 T2,但基于输出 T1 先运行,执行 question(first) 方法,打印问题,设置 flag(true),运行 notify() 方法,执行question(second) 方法 & 进入 wait 方法。现在 T2 启动并执行。
- 为什么直到 T1 调用 Object Chat 的 wait 方法后 T2 才开始。
- 第一次执行 question 方法并调用 notify() 方法时,聊天对象上没有 wait()(因为 t2 尚未开始)。那么,哪个线程监听这个通知方法。
我的代码:
package TestThread;
class Chat {
boolean flag = false;
public synchronized void Question(String msg) {
System.out.println("Question method = " + flag);
if (flag) {
try {
System.out.println("Question method wait start");
wait();
System.out.println("Question method wait finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}
public synchronized void Answer(String msg) {
System.out.println("Answer method = " + flag);
if (!flag) {
try {
System.out.println("Answer method wait start");
wait();
System.out.println("Answer method wait finish");
} 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 MultiThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
结果:-
Question method = false
Hi
Question method = true
Question method wait start
Answer method = true
Hi
Answer method = false
Answer method wait start
Question method wait finish
How are you ?
Question method = true
Question method wait start
Answer method wait finish
I am good, what about you?
Answer method = false
Answer method wait start
Question method wait finish
I am also doing fine!
Answer method wait finish
Great!
【问题讨论】:
-
你可能想看这个,很容易理解:programcreek.com/2009/02/notify-and-wait-example
-
尝试将您的
new T1(m);和new T2(m);分别替换为new T1(m).start()和new T2(m).start()。然后摆脱new Thread(this, "Question").start();和new Thread(this, "Answer").start();。看看这是否使两个线程同时执行。
标签: java multithreading