【发布时间】:2014-06-17 18:58:29
【问题描述】:
我正在运行一个非常简单的多线程程序
主程序
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;
}
我希望两个线程同时/并行运行,类似于这张图片
相反,我得到的是线程 1 先运行然后线程 2 运行的地方
有人可以向我解释为什么会这样吗?
如何让线程同时运行?
【问题讨论】:
-
老兄,首先阅读线程基础知识。线程生命周期从调用 Thread 对象的 start 方法开始,而不是从运行开始。 run 由线程在内部调用以同时执行基于“运行”的任务。
-
将
run公开以及将Thread设为非最终版本肯定是Java API 中最糟糕的设计决策,本可以避免的大量混乱。
标签: java multithreading concurrency parallel-processing