Solved

Synchronization Help

Posted on 2000-05-14
2
165 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

Suggested Solutions

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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 “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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…

808 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