简体   繁体   中英

Simple Threads Behaviour in Java

/* Multiple Threads Executing
 * Author Myth17
 */

class T1 implements Runnable
{
    public void run()
    {
        for(int c=0;c<10;c++)
        System.out.println(Thread.currentThread().getName()+" running....");
    }
}

class T2 implements Runnable
{
    public void run()
    {
        for(int c=0;c<10;c++)
        System.out.println(Thread.currentThread().getName()+" running....");
    }
}


class T3 implements Runnable
{
    public void run()
    {
    for(int c=0;c<10;c++)   
    System.out.println(Thread.currentThread().getName()+" running....");    
    }
}

class Rt
{
    public static void main(String args[])
    {
        T1 j1=new T1();
        T2 j2=new T2();
        T3 j3=new T3();

        Thread w1=new Thread(j1);
        w1.setName("S");
        Thread w2=new Thread(j2);
        w2.setName("N");
        Thread w3=new Thread(j3);
        w3.setName("M");

        w1.start();
        w2.start();
        w3.start();
    }
}

If the loop runs up to 3 in the three for loops, in Linux Java JVM each thread executes serially as SSSNNNMMM (9 lines).

I changed the loop to run up to 10 in each for loops. I was expecting 30 lines and a change in order. But strangely S never executes and program exits!!

Shouldn't S get its chance sooner or later? As what I have read is that apart from deamon threads JVM shuts only after user thread complete.

alt text http://img36.imageshack.us/img36/6646/69458021.png

Did you realize that there are 8 lines of N in your output folder and 10 lines of M . It seems that the output window just displays 18 lines. S runs but you cannot see it.

Can you try incrementing loop to 20 instead of 10. I guess you will just see 18 lines of M .

(It seems that the problem is just not having a scroll bar on output window. Resize should work if exists.)

In your snippet neither of the threads are daemon. And until you set the threads as daemon via Thread#setDaemon() all the threads will execute completely before the app exits.

Recheck your problem!!

This should have worked. You could put log in the run() methods or debug it using break points.

You only have 18 lines showing in the window.

All of the "S" lines have scrolled off, as well as two of the "N" lines.

I tried running your code on a Windows Sun JVM 1.6 and as expected, I got 30 lines. What kind of JVM are you using? All non daemon threads should finish before the JVM exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM