我试图编写一个使用线程但无法理解o/p的程序。我有2个线程:s
和t
。但我看不到线程s
正在工作。线程行为:Java初学者
任何人都可以向我解释行为吗?由于
我的代码:
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
在主thread0
里面runfirst线程
里面runfirst线程
在子线程0
在子线程1
在子线程2
在主线程1
在孩子thread3
在孩子thread0
在子线程1
在子线程2
在孩子thread3
在孩子thread4
在主线程2
在子线程中4
在主线程中3
在主线程4
只是为了让你知道:每当你像这样设计你的代码时,上帝杀死了一只小猫。 – 2012-03-31 01:00:43
考虑让每个线程都有一个'Thread.sleep(1000)'。该参数以毫秒为单位。 – 2012-03-31 01:04:00