为什么并不运行线程?

Com*_*erd 0 java parallel-processing concurrency multithreading

我正在运行一个非常简单的多线程程序

主程序

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();

    }
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

我希望两个线程同时/并行运行,类似于这张图片

在此输入图像描述

相反,我得到的是线程1首先运行然后线程2运行

在此输入图像描述

有人可以向我解释为什么会这样吗?

我如何让线程并发运行?

use*_*751 5

因为你打电话t1.run()t2.run()不是t1.start()t2.start().

如果你打电话run,这只是一个普通的方法调用.它就像任何方法一样,直到它完成后才会返回.它不会同时运行任何东西.绝对没什么特别的run.

start是你调用启动另一个线程并run在新线程中调用的"神奇"方法.(start顺便说一句,调用也是一种正常的方法调用.这里面的代码start是神奇的)