请问JAVA中在控制线程终止的时后用run做终止标记的放置位置有没有什么要求?/

class theThread implements Runnable {
    boolean run = true;

    @Override
    public void run() {
        if (run) {
            for (int i = 0; i < 10; ++i) {
                System.out.println(Thread.currentThread().getName() + "----->" + (i + 1));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return;
        }
    }
}

刚刚学到线程,对这个问题很是不解。如果按我这样写的话是不会起到控制线程的作用的,必须把run判断放置在for循环的下面才可以,即:

class theThread implements Runnable {
    boolean run = true;

    @Override
    public void run() {
        for (int i = 0; i < 10; ++i) {
            if (run) {
                System.out.println(Thread.currentThread().getName() + "----->" + (i + 1));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                return;
            }
        }

    }
}

请问各位大佬,这是为什么??

我不知道呀

https://www.cnblogs.com/liyutian/p/10196044.html

main函数目前没看到。猜测你是在main函数中重新给run赋值false的,建议把run变量改成volatile的。
if放在for循环外,第一次就会判断,run为true接着执行for循环。Thread.sleep的含义为当前线程休眠。