Java,多线程

Java, Multithreading

我正在 Java 自学多线程和并发。请帮助我理解这段代码。我正在创建一个带有 'stop' 布尔变量的线程,'run' 方法不断循环,直到主线程在休眠两秒钟后将停止变量设置为 true。但是,我观察到这段代码在无限循环中运行。我在这里做错了什么?

public class Driver {
    public static void main(String[] args) {
        ThreadWithStop threadWithStop = new ThreadWithStop();
        Thread thread = new Thread(threadWithStop);
        thread.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadWithStop.stopThread();
    }
}

class ThreadWithStop implements Runnable {

    private boolean stop;

    public ThreadWithStop() {
        this.stop = false;
    }

    public void stopThread() {
        this.stop = true;
    }

    public boolean shouldRun() {
        return !this.stop;
    }

    @Override
    public void run() {
        long count = 0L;
        while (shouldRun()) {
            count++;
        }
        System.out.println(count+"Done!");
    }
}

嗯,不能保证会停止,但可能会停止。您通过从主线程调用 stopThread()stop 所做的更改不能保证对 ThreadWithStop 可见 ,直到您与其同步不知何故。

实现此目的的一种方法是使用 synchronized 关键字保护对变量的访问 - 参见例如synchronized methods:

上的官方 Oracle 教程

通过以下更改,stop 的更改保证可见。

class ThreadWithStop implements Runnable {

    private boolean stop;

    public ThreadWithStop() {
        this.stop = false;
    }

    public synchronized void stopThread() {
        this.stop = true;
    }

    public synchronized boolean shouldRun() {
        return !this.stop;
    }

    @Override
    public void run() {
        long count = 0L;
        while (shouldRun()) {
            count++;
        }
        System.out.println(count+"Done!");
    }
}