Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

multithreading - How threads work in Java and how their working is different from basic code inside a method?

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");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...