首页 > 解决方案 > 多线程循环仅适用于添加的空 print("") 语句

问题描述

在这段代码中,有 2 个功能相同的 while 循环,但第一个输出的是“GO!” 第二个永远挂起。到底是怎么回事?

public class Tests {
    public static boolean go=false;
    public static void main(String[] args) {
        new TimerThread().start();

        // Loop 1 - Prints "GO!"
        while(true){
            System.out.print("");
            if(go){
                System.out.println("GO!");
                break;
            }
        }

        go=false;
        new TimerThread().start();

        // Loop 2 - Hangs
        while(true){
            if(go){
                System.out.println("GO!");
                break;
            }
        }
    }
    static class TimerThread extends Thread{
        public void run(){
            double timer = System.currentTimeMillis();
            while(timer>System.currentTimeMillis()-3000){
                go=false;
            }
            go=true;
        }
    }
}

标签: javamultithreading

解决方案


推荐阅读