【发布时间】:2012-04-14 16:10:53
【问题描述】:
我试图编写一个使用线程的程序,但无法理解 o/p。我有 2 个线程:s 和 t。但我看不到线程 s 正在工作。
谁能向我解释一下这种行为?谢谢
我的代码:
public class Bground implements Runnable
{
Thread t,s;
Bground()
{
t = new Thread(this,"first thread");
s = new Thread(this,"second thread");
s.start();
t.start();
}
public void run()
{
System.out.println("inside run" + t.getName());
try
{
for (int i = 0; i < 5; i++)
{
System.out.println("In child thread" + i);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String argv[])
{
Bground b = new Bground();
try
{
for (int i = 0; i < 5; i++)
{
System.out.println("In main thread" + i);
Thread.sleep(1);
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
O/P:
c:\Program Files\Java\jdk1.6.0_23\bin>java Bground
在主线程0
在 runfirst 线程内
在 runfirst 线程内
在子线程0
在子线程1
在子线程2
在主线程1
在子线程3
在子线程0
在子线程1
在子线程2
在子线程3
在子线程4
在主线程2
在子线程4
在主线程3
在主线程4
【问题讨论】:
-
只是让你知道:每次你这样格式化你的代码,上帝杀死一只小猫。
-
考虑让每个线程都有一个
Thread.sleep(1000)。参数以毫秒为单位。
标签: java multithreading