简体   繁体   English

为什么此代码不是“线程安全的”?

[英]Why is this code not 'thread-safe'?

class ThreadUnsafe 
{ 
    static int  val1,  val2; 
    static void Go()
    { 
        if  (val2 != 0)  System.out.println( val1 / val2); 
        val2=0; 
    } 
} 

Apparently the Go() method in this code is not considered "thread-safe". 显然,此代码中的Go()方法不被视为“线程安全”。 Why is this? 为什么是这样?

Normally in Java when concurrency is expected to be an issue either the synchronized keyword would be used on methods that change or read the internal state of the object or a synchronized block would be used with a lock on a non-null object. 通常,在Java中,当期望并发成为问题时,可以在更改或读取对象内部状态的方法上使用synchronized关键字,或者在非null对象上使用锁synchronized对象。 Both would require that accessor methods be created for setting the value of val1 and val2. 两者都需要创建访问器方法来设置val1和val2的值。

Example using synchronized on the methods that change (or read) internal state: 在更改(或读取)内部状态的方法上使用同步的示例:

class ThreadSafe
{
    private static int val1;
    private static int val2;

    static synchronized void go()
    {
        if (val2 != 0)
        {
            System.out.println(val1 / val2);
        }

        val2 = 0;
    }

    static synchronized void setVal1(int newVal1)
    {
        val1 = newVal1;
    }

    static synchronized void setVal2(int newVal2)
    {
        val2 = newVal2;
    }
}

In this case because the methods are static, the synchronization will occur on the class itself. 在这种情况下,因为方法是静态的,所以同步将发生在类本身上。

Example using synchronization on a non-null object: 在非null对象上使用同步的示例:

class ThreadSafe
{
    private static int val1;
    private static int val2;

    private static Object lock = new Object();

    static void go()
    {
        synchronized (lock)
        {
            if (val2 != 0)
            {
                System.out.println(val1 / val2);
            }

            val2 = 0;
        }
    }

    static void setVal1(int newVal1)
    {
        synchronized (lock)
        {
            val1 = newVal1;
        }
    }

    static synchronized void setVal2(int newVal2)
    {
        synchronized (lock)
        {
            val2 = newVal2;
        }
    }
}

See also What does 'synchronized' mean? 另请参见“同步”是什么意思?

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

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