在下面的代码中,我期望只有两个线程之一进入halt()
函数然后停止程序。但似乎两个线程都进入了synchronized
halt() 函数。为什么会发生这种情况??
package practice;
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
Runtime r = Runtime.getRuntime();
halt();
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
synchronized void halt() throws InterruptedException
{
System.out.println(name + " entered synchronized halt");
Runtime r = Runtime.getRuntime();
Thread.sleep(1000);
r.halt(9);
System.out.println(name + " exiting synchronized halt"); // This should never execute
}
}
class Practice{
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting."); // This should never execute
}
}