Java:线程之间的变量同步

MrG*_*MrG 0 java multithreading

我试图以下列方式启动/停止Java线程.

public class ThreadTester {
    public static void main(String[] args) {
        MyThread mt;
        int max = 3;

        for (int i = 0; i < max; i++) {
            mt = new MyThread();
            mt.start();
            mt.finish();
        }
    }
}

public class MyThread extends Thread {
    private volatile boolean active;

    public void run() {
        this.active = true;
        while (isActive()) {
            System.out.println("do something");
        }
    }

    public void finish() {
        this.active = false;
    }

    public boolean isActive() {
        return active;
    }
}
Run Code Online (Sandbox Code Playgroud)

只有当max <= 2时,一切都按预期工作.否则一些线程继续输出,但isActive应该返回false.这至少是我的期望.

问题是:在"master"和"slave"线程之间同步变量的正确方法是什么?

Ale*_*yak 7

您应该在声明期间初始化activetruenot而不是在run方法中初始化.

public class MyThread extends Thread {
    private volatile boolean active = true;

    public void run() {
        // this.active = true;
        while (isActive()) {
            // do nothing
        }
    }

    public void finish() {
        this.active = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

你这样做的方式是竞争条件.

此外,安全停止线程的更好方法是使用中断.