public class SrThread2
{
public static void main(String args[])
{
SubThread another=new SubThread(); //Name is Thread-0
another.start(); //启动线程another
while(another.isAlive())
{
try{Thread.sleep(100);} //让主线程睡眠100毫秒
catch(InterruptedException e){return;}
System.out.println("mainthread is running");
}
}
}
class SubThread extends Thread //定义Thread的子类,这是用户定义的线程
{
public void run()
{
for (int i=0;i<3;i++)
{
System.out.println(this.getName()+" is running");
try{this.sleep(100);} //线程anotherThread睡眠100毫秒
catch(InterruptedException e){}
}
}
}我总觉得main线程不应和系统生成的线程等同地位.这个程序的输出结果,main没有一点特权.不是很理解.
{
public static void main(String args[])
{
SubThread another=new SubThread(); //Name is Thread-0
another.start(); //启动线程another
while(another.isAlive())
{
try{Thread.sleep(100);} //让主线程睡眠100毫秒
catch(InterruptedException e){return;}
System.out.println("mainthread is running");
}
}
}
class SubThread extends Thread //定义Thread的子类,这是用户定义的线程
{
public void run()
{
for (int i=0;i<3;i++)
{
System.out.println(this.getName()+" is running");
try{this.sleep(100);} //线程anotherThread睡眠100毫秒
catch(InterruptedException e){}
}
}
}我总觉得main线程不应和系统生成的线程等同地位.这个程序的输出结果,main没有一点特权.不是很理解.
为什么要给main线程特权呢。如果你需要的话你可以提高它的优先级。
--------------------Configuration: <Default>--------------------
Thread-0 is running
mainthread is running
Thread-0 is running
mainthread is running
Thread-0 is running
mainthread is running
mainthread is runningProcess completed.
我的理解,是应该Thread-0全部执行完,才输出mainthread is running这一句(是在一个循环里的)
{
try{Thread.sleep(100);} //这个Thread为什么一定指的是main主线程
catch(InterruptedException e){return;}
System.out.println("mainthread is running");
}
{
public void run()
{
for (int i=0;i<3;i++)
{
System.out.println(this.getName()+" is running");
/* try{this.sleep(100);} //如果这里被注销掉,那么请看输出结果:
catch(InterruptedException e){}*/
}
}
}--------------------Configuration: <Default>--------------------
Thread-0 is running
Thread-0 is running
Thread-0 is running //这里既然线程已经 dead了
//不符合isAlive()的条件,为什么下边这句还能执行.??
mainthread is runningProcess completed.
2.100时间太太太小了,可忽略不计,main线程必然和Thread-0交差
3.Thread.sleep指的是当前的线程
说明不了什么问题。
你在sleep之前加一句输出看看,
while(another.isAlive())
{
System.out.println(Thread.currentThread());
try{Thread.sleep(100);} //让主线程睡眠100毫秒
catch(InterruptedException e){return;}
System.out.println("mainthread is running");
}
在thinking java里面多线程程序的介绍已经是排在后面了。