The Java™ Tutorials — Concurrency :A Synchronized Class Example 一个同步类的例子
2016-02-18 09:27
423 查看
The Java™ Tutorials — Concurrency :A Synchronized Class Example 一个同步类的例子
原文地址:https://docs.oracle.com/javase/tutorial/essential/concurrency/syncrgb.html
关键点
理解本文案例中,可变对象带来的读取不一致问题。
全文翻译
The class, SynchronizedRGB, defines objects that represent colors. Each object represents the color as three integers that stand for primary color values and a string that gives the name of the color.SynchronizedRGB类定义了表示颜色的对象。每个对象代表了通过三个整数来表示的颜色(这三个整数代表三原色),以及颜色的名字。
public class SynchronizedRGB { // Values must be between 0 and 255. private int red; private int green; private int blue; private String name; private void check(int red, int green, int blue) { if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { throw new IllegalArgumentException(); } } public SynchronizedRGB(int red, int green, int blue, String name) { check(red, green, blue); this.red = red; this.green = green; this.blue = blue; this.name = name; } public void set(int red, int green, int blue, String name) { check(red, green, blue); synchronized (this) { this.red = red; this.green = green; this.blue = blue; this.name = name; } } public synchronized int getRGB() { return ((red << 16) | (green << 8) | blue); } public synchronized String getName() { return name; } public synchronized void invert() { red = 255 - red; green = 255 - green; blue = 255 - blue; name = "Inverse of " + name; } }
SynchronizedRGB must be used carefully to avoid being seen in an inconsistent state. Suppose, for example, a thread executes the following code:
SynchronizedRGB 必须小心使用以避免读取结果不一致。举个例子,假如,一个线程执行了下面的代码:
SynchronizedRGB color = new SynchronizedRGB(0, 0, 0, "Pitch Black"); ... int myColorInt = color.getRGB(); //Statement 1 String myColorName = color.getName(); //Statement 2
If another thread invokes color.set after Statement 1 but before Statement 2, the value of myColorInt won’t match the value of myColorName. To avoid this outcome, the two statements must be bound together:
如果另一个线程在语句1后,语句2前调用了color.set,那么myColorInt和myColorName的值就无法匹配了。为了避免这样的结果,两个语句的执行必须被绑定:
synchronized (color) { int myColorInt = color.getRGB(); String myColorName = color.getName(); }
This kind of inconsistency is only possible for mutable objects — it will not be an issue for the immutable version of SynchronizedRGB.
此样的不一致性仅对可变对象而言,这在不可变版本的SynchronizedRGB中并不是问题。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序