The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The class, SynchronizedRGB
, defines objects that represent colors. SynchronizedRGB
类定义表示颜色的对象。Each object represents the color as three integers that stand for primary color values and a string that gives the name of the color.每个对象都将颜色表示为三个整数(表示主颜色值)和一个字符串(表示颜色名称)。
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. SynchronizedRGB
必须小心使用,以避免在不一致的状态下出现。Suppose, for example, a thread executes the following code:例如,假设一个线程执行以下代码:
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 如果另一个线程在语句1之后但在语句2之前调用color.set
after Statement 1 but before Statement 2, the value of myColorInt
won't match the value of myColorName
. color.set
,则myColorInt
的值将与myColorName
的值不匹配。To avoid this outcome, the two statements must be bound together:为了避免这种结果,这两种说法必须结合在一起:
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
的不可变版本来说,这不是一个问题。