为什么不让线程同时运行? [英] Why arent the threads running concurrently?
问题描述
我正在运行一个非常简单的多线程程序
I am running a very simple multi thread 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
相反,我在线程1首先运行然后线程2运行的地方得到这个信息
Instead I am getting this where thread 1 runs first then thread 2 runs
有人可以向我解释为什么会这样吗?
我如何使线程同时运行?
推荐答案
因为您调用了t1.run()
和t2.run()
而不是t1.start()
和t2.start()
.
Because you called t1.run()
and t2.run()
instead of t1.start()
and t2.start()
.
如果您调用run
,那只是一个普通的方法调用.就像任何方法一样,它直到完成才返回.它不会同时运行任何东西. run
绝对没有什么特别的.
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
是用于启动另一个线程并在新线程中调用run
的魔术"方法. (顺便说一句,调用start
也是正常的方法调用.start
中的代码起到了神奇的作用)
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)
这篇关于为什么不让线程同时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!