Solved

Synchronization Help

Posted on 2000-05-14
2
156 Views
Last Modified: 2010-04-01
Hiya,
  Can someone please tell me what the output to the following sample will be and more importantly, why? Please ignore
any typos.

pulbic class t_4 extends Thread{
   
    public synchronized void run(){
        System.err.println("-->");
        try{
            sleep(1000);
        }
        catch( InterruptedException e ){
        }
        System.err.println("<--");
    }

    public static void main( String args[]){
        t_4 at4 = new t_4();
        at4.start();
        at4.run();
    }
}
0
Comment
Question by:pipe
2 Comments
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 50 total points
ID: 2808610
Well, after you fix the syntax error ("pulbic" should be "public"), you can compile and run the class to get this output on the err stream:

    -->
    <--
    -->
    <--

Here is what is happening. The class extends Thread and overrides the run method to provide some useful behavior. In main, you create an instance of this class and, since it is a Thread, call the start method. When start is called, the thread begins execution and the JVM calls the run method. When the run method terminates, the thread is also terminated.

Note that the at4.start method call returns immediately. At this point, there are two application threads executing concurrently. Of course, only one thread can execute at a time on a single processor system. The "main" thread is the one on which your main method is invoked by the JVM. Technically, this thread has not yielded its timeslice yet so it is free to go ahead and directly invoke the run method of the at4 object. There isn't any problem with this. The run method is just like any other public method of any other object.

Now to the core of why you always get the paired output. It seems that, if I have two threads running simultaneously, given the implementation of the run method with the one second sleep, you should get output like this:

    -->
    -->
    <--
    <--

Why isn't this the result? First, note that it is _not_ the start method that directly calls the run method of your Thread object. The start method simply "schedules" the execution of the new thread with the JVM. When it is time to swap tasks, the JVM knows to begin execution of this new thread by calling the run method. As a result, the run method isn't invoked prior to start returning. Furthermore, and here is the key, the run method of this object can only be executing on one thread at a time because you have declared it to be "synchronized". Since the main thread gets to execute the run method of the at4 object first, that method call will run to completion before it can be executed on any other thread. That effectively prevents both threads from entering the method simultaneously, resulting in pairs of output.

Try this. Remove the synchronized keyword from the method declaration. Compile and run. How does this change the output?

Here is another experiment. Change your printlns to
        System.err.println(Thread.currentThread().getName() + " -->");
and
        System.err.println(Thread.currentThread().getName() + " <--");

This will prepend the name of the thread which is producing the output. Try it with run declared as synchronized and then without synchronized. This might help you visualize what is occuring.

Best regards,
Jim Cakalic
0
 

Author Comment

by:pipe
ID: 2808700
Thank you! Seeing the thread name really cleared things up.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now