Java 为什么线程不能同时运行?

Java 为什么线程不能同时运行?,java,multithreading,concurrency,parallel-processing,Java,Multithreading,Concurrency,Parallel Processing,我正在运行一个非常简单的多线程程序 主程序 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(); } }

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

主程序

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;
}
包javathread;
导入java.util.Random;
公共类JThread实现Runnable
{
JThread(int-limit,int-threadno)
{
t=新螺纹();
这个极限=极限;
this.threadno=threadno;
}
公开募捐
{
随机生成器=新随机();

对于(int i=0;i因为你应该
start()
线程,而不是
run()
它。

因为你调用了
t1.run()
t2.run()
而不是
t1.start()
t2.start()

如果调用
run
,这只是一个普通的方法调用。它在完成之前不会返回,就像任何方法一样。它不会同时运行任何东西。
run
绝对没有什么特别之处


start
是一种“神奇”方法,您可以调用它来启动另一个线程,并在新线程中调用
run
。(顺便说一句,调用
start
也是一种普通的方法调用。是
start
中的代码起了神奇的作用)

您不在线程上运行任何东西,只运行可运行的(您的JThread不是线程,它只是一个不可命名的线程)。 要在线程上运行,您需要执行以下操作:

new Thread(myRunnable).start();

在Runnable中创建线程不会做任何事情(就像您在JThread构造函数中所做的那样)。

请查看线程的
生命周期


dude,首先阅读线程基础知识。线程生命周期从线程对象上的call to start方法开始,而不是从run开始。线程在内部调用run以同时执行基于“run”的任务。将
run
公开以及将
thread
设为not final肯定是未来最糟糕的设计决策之一Java API,本可以避免的混乱程度。他的问题更基本:JThread实现Runnable,但它不是一个实际线程(我认为他试图通过在JThread的Ctor中创建一个实际线程来使用它)。我也这么认为。我也花了一段时间才注意到:P