我正在尝试使用线程在 Java 中打印一条语句,其中每个线程都应该打印该语句的一部分。但是,以下代码并不总是以正确的顺序输出语句。
class NewThread implements Runnable {
String msg;
Thread t;
NewThread(String str) {
t = new Thread(this);
msg = str;
}
public void run() {
PrintMsg(msg);
}
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
}
class ThreadDemo {
public static void main(String args[]) {
NewThread t1, t2, t3;
t1 = new NewThread("Humphry Dumprey");
t2 = new NewThread("went to the hill");
t3 = new NewThread("to fetch a pail of water");
t1.t.start();
t2.t.start();
t3.t.start();
try {
t1.t.join();
t2.t.join();
t3.t.join();
} catch (InterruptedException e) {
System.out.println("Main Thread Interrupted");
}
}
}
我怀疑线程间通信有问题。