1

Basically this code has two threads created in two classes, and they are called from the third class. Each thread has a loop, and it sleeps after each iteration.

(code is in the end)

The output is:

CHECK 0 CHECK
CHECK 1 CHECK
run one
in thread1 
CHECK 2 CHECK
run two
in thread2

1) I am not getting any idea why it works this way. I mean it is okay that CHECK 0 CHECK should be printed first. But why does CHECK 1 CHECK get printed before Thread1 (whereas it comes after Thread1 is called in the code) and same for CHECK 2 CHECK and Thread2?

2) If i replace CHECK 2 CHECK with System.exit(0), as in the case above, where printing CHECK 2 CHECK, which is next to Thread2, takes place before running Thread2, Why is System.exit(0) happening after running Thread2 in this case?

Output for second case:

CHECK 0 CHECK
CHECK 1 CHECK
run one
in thread1 
run two
in thread2

Please tell why this is happening? Why are the threads and code in method, getting mixed up this way? I think i don't have any idea about how threads are managed by java. I tried searching a lot, but could not find anything that i could understand.

Code:

public class Thread1 implements Runnable 
{

    public Thread1()
    {
        new Thread(this).start();
    }

    public void run() 
    {
        // TODO Auto-generated method stub
        System.out.println("run one");
        try
        {
            for(int i = 0; i < 5;i++)
            {
                System.out.println("in thread1 ");
                Thread.sleep(1000);
            }
        }
        catch(Exception e)
        {
            //e.printStackTrace();
        }
    }

}

public class Thread2 implements Runnable 
{

    public Thread2()
    {
        new Thread(this).start();
    }

    public void run() 
    {
        // TODO Auto-generated method stub
        System.out.println("run two");
        try
        {
            for(int i=0;i<5;i++)
            {
                System.out.println("in thread2 ");
                Thread.sleep(1000);
            }
        }
        catch(Exception e)
        {
            //e.printStackTrace();
        }
    }
}

public class Threadjava
{
    public static void main(String[] str)
    {
        System.out.println("CHECK 0 CHECK");
        new Thread1();
        System.out.println("CHECK 1 CHECK");
        new Thread2();
        System.out.println("CHECK 2 CHECK");
        //The above is deleted in the second case
        System.exit(0);
        System.out.println("CHECK 3 CHECK");
    }
}
5
  • Can you summarize your knowledge of threads in this post? I think the problem is that you don't understand that threads are supposed to be run completely separate from each other and that there are no guarantees at all in which order things are invoked between threads, unless you use Thread synchronization mechanisms such as the 'synchronized' keyword in Java. Commented Jul 23, 2014 at 14:24
  • It's because it's a thread, and not a method. There are no guarantees about when that thread's run method will be executed. Commented Jul 23, 2014 at 14:25
  • threads are pretty nasty.they are very random, set priority Commented Jul 23, 2014 at 14:31
  • I have learned at university that the priority system of Java does pretty much almost nothing because the system tries to ensure that nobody gets starved out Commented Jul 23, 2014 at 14:33
  • Is it like, there are two things in my method, one is the basic code in method and then there are threads. Threads are running in their own world and the method body in its own? Is it like threads are recognized and then they are run in their different world? Or something like there are three threads (method and the two threads), which are run simultaneously (i mean just like any three threads would work is set to work together)? Commented Jul 23, 2014 at 14:34

4 Answers 4

13

Well, this is a common misconception, that java programs are single threaded by nature, because they are not. When you start a java program it's being executed inside a Java Virtual Machine, which starts several other threads to execute your code. Check this nice blog:

http://blog.jamesdbloom.com/JVMInternals.html#jvm_system_threads

In your case you most important is, that you start a main thread, which executes a main method. From there you start two separate threads Thread1 and Thread2, which are being scheduled to be executed, but you don't know when they will be picked up by the OS scheduler to be actually executed. It's not deterministic for many reasons:

  • you don't know what algorithm scheduler is using to pick up threads to be executed,
  • you don't know how many cores your processors have, your threads might run in parallel or serially
  • Just In Time compiler might rearrange and optimise your code,
  • CPU might rearrange reads and writes to IO to optimise the execution of your code,
  • you might have bugs in your code that lead to data races, race conditions, starvations etc.

Java concurrency is a hard topic and the blog entry that I've sent you is a good place to start, go with it. For serious reading go here http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601.

Good luck.

Sign up to request clarification or add additional context in comments.

Comments

0

I wouldn't really trust on whatever System.out.println() tells me, have you tried debugging and/or flushing the System.out stream after every println?

There are a lot of factors that can affect the way threads are executed, for example, in this case what might be happening is that, by the time that Thread1 is created and run, the main Thread reaches "CHECK 1 CHECK" point, and this is why it's shown first.

I'd recommend you to log the outputs and debug your code and see if the behavior is the same.

Let us know what you discover so we can help you.

Hope this helps (at least a bit) :)

Comments

0

You can't predict in which order threads will be executed unless you control their execution (with mechanism like lock, mutex, semaphore and join).

I think you need more knowledge about concurrency programming.

Here some useful links:

wikipedia's concurrency page

oracle's tutorial (IMHO it's pretty good tutorial)

Comments

0

The execution of threads is quite Random. you can control the execution(by synchronization and all). Refer to docs.oracle for better understanding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.