简体   繁体   English

两个线程访问相同的变量锁定应用程序

[英]Two threads accessing same variable lock application

The following code was summed up the application, the application randomly was locked in 下面的代码总结了该应用程序,该应用程序被随机锁定在

while (flag) while(标志)

This code, running on my machine gets caught, in another machine he finished normally 在我的计算机上运行的这段代码被他正常完成的另一台计算机捕获

The output generated here is: 此处生成的输出是:

INIT
END
before while
before flag
after flag

Code: 码:

package threads;

public class Run implements Runnable {

private Thread thread;
private boolean flag = true;

public void init() {
    thread = new Thread(this);
    thread.setName("MyThread");
    thread.start();
}

@Override
public void run() {
    try {

        int i = 0;
        while (i < 1000) {
            i++;
        }
        System.out.println("before flag");
        flag = false;
        System.out.println("after flag");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        flag = false;
    }
}

public void end() {
    thread.interrupt();
    thread = null;

    System.out.println("before while");
    while (flag) {
        // try { Thread.sleep(100);} catch (InterruptedException e) {}
    }
    ;
    System.out.println("after while");
}

public static void main(String[] args) {
    Run r = new Run();
    System.out.println("INIT");
    r.init();
    System.out.println("END");
    r.end();
}
}

Why when I change the value of flag the main thread does not pass through loop? 为什么当我更改标志的值时主线程不通过循环?

Change 更改

private boolean flag = true;

to

private volatile boolean flag = true;

Without volatile , there is no guarantee the waiting thread needs to see the value get updated. 如果没有volatile ,则不能保证等待线程需要看到该值得到更新。 HotSpot might even inline while(flag) to while(true) if the loop spins enough times. 如果循环旋转了足够的时间, while(true) HotSpot甚至可以将while(flag)内联到while(true)

See Memory Consistency Errors . 请参阅内存一致性错误


Also, what you're doing is called a spinlock . 另外,您正在做的事情称为自旋锁 Normally you should use thread.join() instead. 通常,您应该使用thread.join()代替。 A spinlock is wasteful of resources because the waiting thread is actually working (checking a variable) the entire time it is supposed to be waiting. 自旋锁浪费资源,因为等待线程实际上在应该等待的整个时间都在工作(检查变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM