View Single Post
  #1 (permalink)  
Old 08-14-2007, 10:52 PM
oguz oguz is offline
Member
 
Join Date: Aug 2007
Posts: 1
oguz is on a distinguished road
synchronization question
Hi everyone,
i'm new to forums and java threads.
As i was studying threads, i encountered the two sample classes below:
Code:
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); synchronized (this) { while (suspendFlag) { wait(); } } } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } void mysuspend() { suspendFlag = true; } synchronized void myresume() { suspendFlag = false; notify(); } }
Code:
class SuspendResume { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending thread One"); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming thread One"); ob2.mysuspend(); System.out.println("Suspending thread Two"); Thread.sleep(1000); ob2.myresume(); System.out.println("Resuming thread Two"); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } // 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."); } }
and there are some points i don't understant.
First why are we using synchronized as we are calling wait(). I don't see any way there could be parallel usege.
Second, when i remove the synchronized keyword from the code i get java.lang.IllegalMonitorStateException. After this if i also remove the lines with ob2 i don't get any exception. How come removing ob2 affects ob1 and prevents the program from throwing exception ?

As i said before, i'm new to threads, and if you could help me i would really appriciate it.
Reply With Quote
Sponsored Links