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
Instead I am getting this where thread 1 runs first then thread 2 runs
Can someone explain to me why this is happening ??
How do i get the threads to run concurrently ??
Please go through the
Life Cycle of a Thread
.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:
creating the thread in the Runnable does nothing (like you did in JThread constructor).
Because you should
start()
the Thread, notrun()
it.Because you called
t1.run()
andt2.run()
instead oft1.start()
andt2.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 aboutrun
.start
is the "magic" method that you call to start another thread and callrun
in the new thread. (Callingstart
is also a normal method call, by the way. It's the code insidestart
that does the magic)