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没有一点特权.不是很理解.

解决方案 »

  1.   

    它们的优先级是相同的,都是5,也就是NORM_PRIORITY。
    为什么要给main线程特权呢。如果你需要的话你可以提高它的优先级。
      

  2.   

    我想用neatbeans调试的图贴过来,但是不能贴图,就得了。
      

  3.   

    为什么输出结果是这样:
    --------------------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这一句(是在一个循环里的)
      

  4.   

        while(another.isAlive())
            {
                try{Thread.sleep(100);}          //这个Thread为什么一定指的是main主线程
                catch(InterruptedException e){return;}
                System.out.println("mainthread is running");
            }
      

  5.   

    别的线程的代码都在其run()方法里了。
      

  6.   

    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);}                    //如果这里被注销掉,那么请看输出结果:
                catch(InterruptedException e){}*/  
            }
        }
    }--------------------Configuration: <Default>--------------------
    Thread-0 is running
    Thread-0 is running
    Thread-0 is running   //这里既然线程已经 dead了
                                 //不符合isAlive()的条件,为什么下边这句还能执行.??
    mainthread is runningProcess completed.
      

  7.   

    1.多线程程序遵循时间片轮转
    2.100时间太太太小了,可忽略不计,main线程必然和Thread-0交差
    3.Thread.sleep指的是当前的线程
      

  8.   

    不能孤立的看线程,大部分情况下,main线程中的while(another.isAlive())会执行的比较早,这时候another这个线程还是alive的,但是判断成立之后主线程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");
            }
      

  9.   

    BTW: 无论是什么语言多线程都是最难的一部分,懂得写多线程程序和把多线程程序写好差太远了,多线程程序难调试,难分析,大型程序里面如果多程序出了问题,程序基本就处于高危状态,楼上所言即是,呵呵。
    在thinking java里面多线程程序的介绍已经是排在后面了。
      

  10.   

    本帖最后由 java2000_net 于 2008-10-03 13:12:44 编辑