The Java™ Tutorials - Concurrency: A Synchronized Class Example 동기 화 클래스 의 예

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 를 호출 하면 my ColorInt 와 my ColorName 의 값 이 일치 하지 않 습 니 다.이러한 결 과 를 피하 기 위해 서 는 두 문장의 실행 이 연결 되 어야 합 니 다.
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 에 서 는 문제 가 되 지 않 습 니 다.

좋은 웹페이지 즐겨찾기