程序怎么可能只包含线程安全类,而不是线程安全类? [英] How is it possible for a program to contain exclusively thread-safe classes, but not be thread-safe?

查看:108
本文介绍了程序怎么可能只包含线程安全类,而不是线程安全类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读实践中的Java并发性",作者说:完全由线程安全的类组成的程序可能不是线程安全的".这怎么可能?我似乎不明白,有人可以举个例子吗?

I am reading "java concurrency in practice", and the author says: "A program that consists entirely of thread-safe classes may not be thread-safe". How is this possible? I don't seem to understand, can someone provide an example?

推荐答案

一个示例将是线程安全的类上的单个方法,但如果您调用多个方法,它们不是原子的.例如

An example would be individual methods on a class that are thread safe, but they are not atomic if you invoke more than one. E.g.

if (!threadSafeCollection.contains(thing)) {
  threadSafeCollection.add(thing);
}

如果另一个线程在此线程的containsadd调用之间添加到集合中,则可能会产生错误的结果.

This may yield incorrect results if another thread adds to the collection between the contains and add invocations in this thread.

这篇关于程序怎么可能只包含线程安全类,而不是线程安全类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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