▶ synchronized 선언에 의한 동기화 블록의 구성
class IHaveTwoNum {
int num1=0;
int num2=0;
public void addOneNum1() {
num1 += 1;
}
public void addTwoNum1() {
num1 += 2;
}
public void addOneNum2() {
num2 += 1;
}
public void addTwoNum2() {
num2 += 2;
}
public void showAllNums() {
System.out.println("num1 : " + num1);
System.out.println("num2 : " + num2);
}
}
class AccessThread extends Thread {
IHaveTwoNum twoNumInst;
public AccessThread(IHaveTwoNum inst) {
twoNumInst = inst;
}
public void run() {
twoNumInst.addOneNum1();
twoNumInst.addTwoNum1();
twoNumInst.addOneNum2();
twoNumInst.addTwoNum2();
}
}
public class SyncObjectKey {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
IHaveTwoNum numInst = new IHaveTwoNum();
AccessThread at1 = new AccessThread(numInst);
AccessThread at2 = new AccessThread(numInst);
at1.start();
at2.start();
try{
at1.join();
at2.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
numInst.showAllNums();
}
}
class IHaveTwoNum2 {
int num1 = 0;
int num2 = 0;
public void addOneNum1() {
synchronized (key1) {
num1 += 1;
}
}
public void addTwoNum1() {
synchronized (key1) {
num1 += 2;
}
}
public void addOneNum2() {
synchronized (key2) {
num2 += 1;
}
}
public void addTwoNum2() {
synchronized (key2) {
num2 += 2;
}
}
public void showAllNums() {
System.out.println("num1 : " + num1);
System.out.println("num2 : " + num2);
}
Object key1 = new Object();
Object key2 = new Object();
}
class AccessThread2 extends Thread {
IHaveTwoNum2 twoNumInst;
public AccessThread2(IHaveTwoNum2 inst) {
twoNumInst = inst;
}
public void run() {
twoNumInst.addOneNum1();
twoNumInst.addTwoNum1();
twoNumInst.addOneNum2();
twoNumInst.addTwoNum2();
}
}
public class SyncObjectKeyAnswer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
IHaveTwoNum numInst = new IHaveTwoNum();
AccessThread at1 = new AccessThread(numInst);
AccessThread at2 = new AccessThread(numInst);
at1.start();
at2.start();
try {
at1.join();
at2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
numInst.showAllNums();
}
}
[Java]Byte File Copy 예제. (0) | 2012.09.23 |
---|---|
[Java] wait, notify, notifyAll에 의한 실행순서 동기화 (0) | 2012.09.21 |
[Java]Thread 예제 (0) | 2012.09.17 |
[Java]Iterator를 이용한 인스턴스의 순차적 접근 (0) | 2012.09.16 |
[Java] 문자열 토큰(Token)의 구분 (0) | 2012.09.15 |
댓글 영역