SynchronizedRGB
是表示颜色的类,每一个对象代表一种颜色,使用三个整形数表示颜色的三基色,字符串表示颜色名称。
01 |
public class SynchronizedRGB { |
02 |
03 |
// Values must be between 0 and 255. |
04 |
private int red; |
05 |
private int green; |
06 |
private int blue; |
07 |
private String name; |
08 |
09 |
private void check( int red, |
10 |
int green, |
11 |
int blue) { |
12 |
if (red < 0 || red > 255 |
13 |
|| green < 0 || green > 255 |
14 |
|| blue < 0 || blue > 255 ) { |
15 |
throw new IllegalArgumentException(); |
16 |
} |
17 |
} |
18 |
19 |
public SynchronizedRGB( int red, |
20 |
int green, |
21 |
int blue, |
22 |
String name) { |
23 |
check(red, green, blue); |
24 |
this .red = red; |
25 |
this .green = green; |
26 |
this .blue = blue; |
27 |
this .name = name; |
28 |
} |
29 |
30 |
public void set( int red, |
31 |
int green, |
32 |
int blue, |
33 |
String name) { |
34 |
check(red, green, blue); |
35 |
synchronized ( this ) { |
36 |
this .red = red; |
37 |
this .green = green; |
38 |
this .blue = blue; |
39 |
this .name = name; |
40 |
} |
41 |
} |
42 |
43 |
public synchronized int getRGB() { |
44 |
return ((red << 16 ) | (green << 8 ) | blue); |
45 |
} |
46 |
47 |
public synchronized String getName() { |
48 |
return name; |
49 |
} |
50 |
51 |
public synchronized void invert() { |
52 |
red = 255 - red; |
53 |
green = 255 - green; |
54 |
blue = 255 - blue; |
55 |
name = "Inverse of " + name; |
56 |
} |
57 |
} |
使用SynchronizedRGB时需要小心,避免其处于不一致的状态。例如一个线程执行了以下代码:
1 |
SynchronizedRGB color = |
2 |
new SynchronizedRGB( 0 , 0 , 0 , "Pitch Black" ); |
3 |
... |
4 |
int myColorInt = color.getRGB(); //Statement 1 |
5 |
String myColorName = color.getName(); //Statement 2 |
如果有另外一个线程在Statement 1之后、Statement 2之前调用了color.set方法,那么myColorInt的值和myColorName的值就会不匹配。为了避免出现这样的结果,必须要像下面这样把这两条语句绑定到一块执行:
1 |
synchronized (color) { |
2 |
int myColorInt = color.getRGB(); |
3 |
String myColorName = color.getName(); |
4 |
} |
这种不一致的问题只可能发生在可变对象上。
文章转自 并发编程网-ifeve.com