상세 컨텐츠

본문 제목

[Java]동기화 기법 예제.

JAVA Language

by mobile 2012. 9. 20. 00:56

본문

반응형

▶ 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();

}

}


반응형

관련글 더보기

댓글 영역