brucecloud 2015-07-13 06:08 采纳率: 25%
浏览 1362
已采纳

Java 多线程问题求解....

public class SigleThread extends Thread {

@Override
public void run() {
    for (int i = 0; i < 5; i++) {
        System.out.println(i);
        try {
            join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

public class Test {
public static void main(String[] args) {
SigleThread sing = new SigleThread();
sing.start();
}
}

这个时候控制台在输出0之后....就会处于卡死状态....为什么会这样????求大神解惑~~~

而换成下面这种调用方式就没问题....

public class Test {
public static void main(String[] args) {
Runnable sing = new SigleThread();
Thread t = new Thread(sing);
t.start();
}
}

这种调用就会打印0 1 2 3 4 5然后正常结束....请问到底是什么原理??

  • 写回答

2条回答 默认 最新

  • Brankily 2015-07-13 08:14
    关注

    主要的原因是楼主没搞清楚,run方法里面的this指的是谁。

    看我贴的代码,楼主拿去运行下this是谁。语句后面我写了注释,楼主注意看下。

     public class SigleThread extends Thread{
        @Override
        public void run() {
    
            System.out.println(this); //this是 sing对象
    
            System.out.println(this.isAlive()); //sing是个线程,但是此线程并没有start,它不是活的
    
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
                try {
                    this.join(); //关键是在这里。join时检测this是否是活的(可以去看下join的源码),也就是检测isAlive是不是返回true。
                                //如果是,则线程等待,即wait(0),在没有被notify之前,就阻塞在那里。也就是楼主说的卡死在那里了。
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
     public class Test {
        public static void main(String[] args){
    
            Runnable sing = new SigleThread();//new了一个线程。叫Thread-0
            System.out.println(sing);
            Thread t = new Thread(sing);//又new了一个线程。叫Thread-1。Thread-1启动后,run方法里面的this是指sing,而不是t自己,执行的是sing的run方法。
            System.out.println(t);
            t.start(); //Thread-1启动。但Thread-0并没有启动。
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记