本文介绍了Java:线程之间的变量同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试通过以下方式启动/停止Java线程.

I'm trying to start/stop Java threads in the following way.

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;
    }
}

只有在max< = 2时,所有内容才能按预期工作.否则,尽管isActive应该返回false,但某些线程继续其输出.那至少是我的期望.

Everything works as expected only if max <= 2. Otherwise some threads continue with their output, although isActive should return false. That was at least my expectation.

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

推荐答案

您应该在声明过程中将active初始化为true,而不是在run方法中.

You should initialize active to true during declaration and NOT in a run method.

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;
    }
}

您的操作方式存在竞争状况.

The way you are doing it there is a race condition.

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

Also, the better approach for safely stopping a thread is to use interruption.

这篇关于Java:线程之间的变量同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:18
查看更多