Why arent the threads running concurrently?

2019-08-16 19:28发布

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

4条回答
等我变得足够好
2楼-- · 2019-08-16 19:57

Please go through the Life Cycle of a Thread.

enter image description here

查看更多
我想做一个坏孩纸
3楼-- · 2019-08-16 20:05

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

查看更多
家丑人穷心不美
4楼-- · 2019-08-16 20:11

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

查看更多
你好瞎i
5楼-- · 2019-08-16 20:12

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)

查看更多
登录 后发表回答