x86timesxx 2011-01-21 22:41
浏览 225
已采纳

谁能给我分析下这个程序的运行步骤

package thread;

public class Test_Sleep extends Thread {
boolean flag = true;

public void run() {
    while (flag) {
        try {
            System.out.println("step    1" );
            sleep(50);
            if (!this.isAlive()) {
                System.out.println("thread is over...");
            }else {
            System.out.println("step    2" );
            System.out.println("step    3" );
            System.out.println("step    4" );
            System.out.println("step    5" );
            System.out.println("step    6" );
            System.out.println("step    7" );
            System.out.println("step    8" );
            System.out.println("step    9" );
            System.out.println("step    10" );
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

public static void main(String[] args) {
    Test_Sleep t = new Test_Sleep();
    t.start();
    try {
        System.out.println("main before sleep ..." );
        Thread.sleep(100);
        System.out.println("main after sleep ..." );
        t.flag=false;
        System.out.println("thread is over...");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }



}

}

运行结果是:
main before sleep ...
step 1
step 2
step 3
step 4
step 5
step 6
step 7
step 8
step 9
step 10
step 1
main after sleep ...
thread is over... //下面的为什么还能打印出来?????????????
step 2
step 3
step 4
step 5
step 6
step 7
step 8
step 9
step 10

  • 写回答

1条回答 默认 最新

  • weixin_42406059 2011-01-22 00:32
    关注

    thread is over...不是if (!this.isAlive())这个条件中打出来的。
    你把flag设置成false时,已经进入了下一个循环,并且循环没有结束,此时thread仍然是alive的,这个循环走完后,thread才结束,你在t.flag=false后再Thread(100)就可以看到thread结束了,因为循环已经走完了。
    在逻辑中不应该使用isAlive进行判断,而应该根据flag的值进行判断。即将条件改为if (!flag)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?