public class Test {    public  static boolean flag=false;
    private static Runnable run=new Runnable() {
        @Override
        public void run() {
            while (true){
         //       System.out.println();  ①
                if (flag){
                    System.out.println("this is sub thread..........................");
                }
            }
        }
    };
    public static void main(String[] args) throws InterruptedException {
        new Thread(run).start();
        Thread.sleep(1000);
        flag=true;
    }
}
如题,子线程里的代码是不可能执行的,但是把①处的注释放开,子线程里的代码就可以执行。请问各路大神,是什么原因呢?

解决方案 »

  1.   

    你主线程要等待i。不然直接进程退出了。可见性要用volatile
      

  2.   

    是一个死循环,没有显示是因为在死循环里面,显示的同样的内容。public class Test {
     
        public  static boolean flag=false;
        private static Runnable run=new Runnable() {
            @Override
            public void run() {
                while (true){
                  System.out.println("***********"); 
                    if (flag){
                        System.out.println("this is sub thread.........................."+new java.sql.Timestamp(System.currentTimeMillis()).toString());
                    }
                }
            }
        };
        public static void main(String[] args) throws InterruptedException {
            new Thread(run).start();
            Thread.sleep(1000);
            flag=true;
        }
    }
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:44:54.313
    ***********
    this is sub thread..........................2018-07-02 08:4