views:

108

answers:

5
/* 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

+1  A: 

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

fastcodejava
+2  A: 

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!!

Suraj Chandran
the threads must be marked as user threads - `setDaemon(false)`, not as daemon threads. If threre are only daemon threads, the JVM will exit. The default already is to create user threads. (*ucuz*)
Carlos Heuberger
A: 

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.

Ehrann Mehdan
+4  A: 

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.)

JCasso
Checked...Lines scrolled off.. :)
Myth17
+1  A: 

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.

UncleO