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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制