Discuss / Java / volatile 的理解和其他的一些并发理解

volatile 的理解和其他的一些并发理解

Topic source

无故之秋

#1 Created at ... [Delete] [Delete and Lock User]

volatile关键字解决的是可见性问题:当一个线程修改了某个共享变量的值,其他线程能够立刻看到修改后的值。

本想验证上面的这句话,却加强了并发的理解。

下面是我执行的代码:

public class TestMain {    public static void main(String[] args) throws InterruptedException {        HelloThread t = new HelloThread();        t.start();        Thread.sleep(10);        t.running = false;    // p1        t.running = true;    // p2    }}class HelloHThread extends Thread {    volatile boolean running = true;    @Override    public void run() {        int n = 0;        while (running) {  // p3            n++;      // p4            System.out.println(n + " hello!");    // p5        }        System.out.println("end");    }}

以上代码大概率会一直执行HelloThread线程。

个人理解:main线程p1的代码会将running标志位修改为false,此时HelloThread线程执行的代码是p3时,HelloThread线程就会到Terminated状态,但如果正在执行 p4或p5,而main线程又并发的执行了p2的代码,那么HelloThread线程就会永远执行。

Barton

#2 Created at ... [Delete] [Delete and Lock User]

我在你代码的基础上加上了t.join()证实了你的理解是正确的,

一直运行HelloThread的原因是运行起初运行HelloThread时,即使将标志位改为False,但是由于Main线程将标志位并发修改成了True,故永远执行HelloThread

//原代码
public class test {
    public static void main(String[] args) throws InterruptedException {
        HelloThread t = new HelloThread();
        t.start();
        Thread.sleep(10);
        t.running = false;    // p1
        t.running = true;    // p2
        }
    }
class HelloThread extends Thread {
    volatile boolean running = true;
    @Override
    public void run(){
        int n = 0;
        while (running){  // p3
            n++;      // p4
            System.out.println(n + " hello!");    // p5
        }        
        System.out.println("end");
        }
    }
//修改后
public class test {
    public static void main(String[] args) throws InterruptedException {
        HelloThread t = new HelloThread();
        t.start();
        Thread.sleep(10);
        t.running = false;    // p1
        t.join();
        t.running = true;    // p2
        }
    }
class HelloThread extends Thread {
    volatile boolean running = true;
    @Override
    public void run(){
        int n = 0;
        while (running){  // p3
            n++;      // p4
            System.out.println(n + " hello!");    // p5
        }        
        System.out.println("end");
        }
    }

  • 1

Reply