?
Solved

Synchronization Help

Posted on 2000-05-14
2
Medium Priority
?
175 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Introducing Priority Question

Increase expert visibility of your issues by participating in Priority Question, our latest feature for Premium and Team Account holders. Adjust the priority of your question to get emergent issues in front of subject-matter experts for help when you need it most.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month14 days, 14 hours left to enroll

770 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