使用volatile或atomic boolean停止runnable线程的问题

时间:2015-03-25 18:57:24

标签: java multithreading

我试图使用volatile变量或原子变量来停止正在运行的线程。但我对此有些怀疑。以下是我试过的代码。

public class DemoThread {
class DemoRunnable implements Runnable {

    private String name;

    public volatile boolean isRunning = true;

    public DemoRunnable() {
    }

    public DemoRunnable(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public synchronized boolean isRunning() {
        return isRunning;
    }

    public synchronized void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    @Override
    public void run() {

        System.out.println(" runnable ..." + name + " isRunning "
                + isRunning);

        while (isRunning) {
            int i;
            for (i = 0; i < 100; i++) {
                System.out.println("--------------------> i " + i
                        + " name " + name + " isRunning " + isRunning);
            }
            // if (i > 0) {
            // System.out.println(" volatile not working ");
            // throw new RuntimeException("volatile not working " + name);
            // }
        }
        System.out.println(" run method ends ..." + isRunning);
    }

}

private void demoStop(int count) {
    DemoRunnable runnable1 = new DemoRunnable("" + count);

    Thread t1 = new Thread(runnable1);
    Thread t2 = new Thread(runnable1);

    t1.start();
    t2.start();

    runnable1.isRunning = false;
    // runnable1.setRunning(false);

}

public static void main(String[] args) {
    DemoThread demoThread = new DemoThread();

    for (int i = 0; i < 200; i++) {
        try {
            demoThread.demoStop(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

}

Wile执行上面的代码有时包含while循环的run方法已被执行多次。一旦isStopped设置为false,是否可以阻止while循环运行?

线程的中断方法不会停止运行方法。

我尝试了isStop变量的原子布尔和同步方法,但结果相同。

1 个答案:

答案 0 :(得分:1)

如果您的可运行检查是中断的,则中断()将按预期停止。

    @Override
public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        someTask();
        // thread can sleep if you like, add this block  
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            log.warn("Interrupted", e);
            break;
        }
    }
}

你的嵌套循环不检查原子布尔值,自然不会停止。无论如何,interrupt()比lame布尔标志好得多。有关详细信息,请参阅ExecutorService和Future。