gpt4 book ai didi

java - 为什么线程不同时运行?

转载 作者:行者123 更新时间:2023-12-01 07:06:13 25 4
gpt4 key购买 nike

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

主程序

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;
}

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

enter image description here

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

enter image description here

有人可以向我解释为什么会发生这种情况吗?

如何让线程同时运行?

最佳答案

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

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

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

关于java - 为什么线程不同时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com