In the following code I was expecting only one of the two threads to enter the halt() function and then halt the program. But it seems as if both the threads are entering into the synchronized halt() function. Why could this be happening??
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 } }