Question

I am running a very simple multi thread program

Main program

package javathread;


public class JavaThread {


    public static void main(String[] args) 
    {

        JThread t1 = new JThread(10,1);
        JThread t2 = new JThread(10,2);

        t1.run();
        t2.run();

    }
}

JThread.java

package javathread;

import java.util.Random;

public class JThread implements Runnable
{
    JThread(int limit , int threadno)
    {
        t = new Thread();
        this.limit = limit;
        this.threadno = threadno;

    }

    public void run()
    {
        Random generator = new Random();

        for (int i=0;i<this.limit;i++)
        {
            int num = generator.nextInt();

            System.out.println("Thread " + threadno + " : The num is " + num   );
            try
            {
            Thread.sleep(100);
            }
            catch (InterruptedException ie)
            {

            }
        }

    }




    Thread t;
    private int limit;
    int threadno;
}

I expect both threads to run concurrently/parrallel , something similar to this picture

enter image description here

Instead I am getting this where thread 1 runs first then thread 2 runs

enter image description here

Can someone explain to me why this is happening ??

How do i get the threads to run concurrently ??

Was it helpful?

Solution

Because you called t1.run() and t2.run() instead of t1.start() and t2.start().

If you call run, it's just a normal method call. It doesn't return until it's finished, just like any method. It does not run anything concurrently. There is absolutely nothing special about run.

start is the "magic" method that you call to start another thread and call run in the new thread. (Calling start is also a normal method call, by the way. It's the code inside start that does the magic)

OTHER TIPS

Please go through the Life Cycle of a Thread.

enter image description here

you don't run anything on the Thread, you just run the Runnable (your JThread is NOT a thread, it is just a unnable). to run on a thread, you need to do something like this:

new Thread(myRunnable).start();

creating the thread in the Runnable does nothing (like you did in JThread constructor).

Because you should start() the Thread, not run() it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top