[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Synchronization Help

Posted on 2000-05-14
2
Medium Priority
?
181 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 200 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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 functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses
Course of the Month19 days, 6 hours left to enroll

834 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