Java在两个线程之间共享一个变量 [英] Java share a variable between two threads

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

问题描述

我有两个线程。一个调用一个修改变量的类的update方法。另一个调用读取变量的类的update方法。只有一个线程写入,一个(或多个)线程读取该变量。

I have two threads. One invokes the update method of a class that modifies a variable. Another invokes the update method of a class that reads the variable. Only one thread writes and one (or more) threads read that variable. What do I need to do in terms of concurrency, since I am new to multi-threading?

public class A
{
    public int variable; // Does this need to be volatile?
       // Not only int, could also be boolean or float.
    public void update()
    {
        // Called by one thread constantly
        ++variable;
        // Or some other algorithm
        variable = complexAlgorithm();
    }
}

public class B
{
    public A a;
    public void update()
    {
        // Called by another thread constantly
        // I don't care about missing an update
        int v = a.variable;
        // Do algorithm with v...
    }
}

谢谢,

推荐答案

如果只有一个线程写入变量你可以逃避使它 volatile 。否则,请参阅 AtomicInteger 的答案。


只有 volatile 会在只有一个写线程的情况下工作,因为只有一个写线程,所以它总是有正确的值变量

If there is one and only one thread that writes to variable you can get away with making it volatile. Otherwise see the answer with AtomicInteger.

Only volatile will work in case of only one writing thread because there is only one writing thread so it always has the right value of variable.

这篇关于Java在两个线程之间共享一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆