관리 메뉴

nkdk의 세상

자바 Language 13일째 1번째 본문

My Programing/JAVA

자바 Language 13일째 1번째

nkdk 2008. 3. 8. 01:11
자 오늘은 자바 처리를 할 때 동기화에 대해서 배웠습니다.

package Thread;

public class Bank {
private int money=10000; // 공유될 자원
public int getMoney() {
return money;
}
public void setMoney(int money){
try{
Thread.sleep(3000);
}catch(Exception ex){}
this.money=money;
}
public synchronized void saveMoney(int save) {
int m=this.getMoney();
try{
Thread.sleep(5000);
}catch(Exception ex){}
this.setMoney(m + save);
}
public synchronized void minusMoney(int save) { // synchronized 라는 명령으로 자원을 공유한다.(쓰레드의 자원 공유)
int m=this.getMoney();
this.setMoney(m - save);
}
}


---

package Thread;

public class Park extends Thread{
public void run() {
SyncTest.mybank.saveMoney(5000);
System.out.println("5000원 예금: 잔고==> " + SyncTest.mybank.getMoney());
}

}


---

package Thread;

public class ParkWife extends Thread{
public void run() {
SyncTest.mybank.minusMoney(1000);
System.out.println("1000원 출금금: 잔고==> " + SyncTest.mybank.getMoney());
}

}

---

package Thread;

public class SyncTest {
public static Bank mybank=new Bank();
Thread t1;
public static void main(String[] args) {
System.out.println("원금: "+mybank.getMoney());
Park p=new Park();
ParkWife w=new ParkWife();
p.start();
try{
Thread.sleep(400);
}catch(Exception ex){}
w.start();
}
}

--

자 여기서 부터는 화일이 하나 입니다.
package Thread;

class BreadPlate{
private int breadcount=0;
public BreadPlate() {

}
public synchronized void makeBread() {
if(breadcount>10) try {
System.out.println("빵이 남는다.");
wait();
} catch(Exception ex) {}
breadcount++;
System.out.println("빵 만듬 총: "+breadcount+" 개");
this.notifyAll(); // 데드락에 안 빠질 수도 있지만 빠질 수도 있기 때문에 notify 한다.
}

public synchronized void eatBread(){
if(breadcount<1) try {
System.out.println("빵이 모자라 기다린다.");
wait();
} catch(Exception ex) {}
breadcount--;
System.out.println("빵 먹음 총: "+breadcount+" 개");
this.notifyAll();
}
}

class BreadMaker extends Thread{
private BreadPlate bread;
public BreadMaker(BreadPlate bread) {
this.bread=bread;
}
public void run(){
for(int i=0;i<30;i++)
bread.makeBread();
}
}
class BreadEater extends Thread{
private BreadPlate bread;
public BreadEater(BreadPlate bread) {
this.bread=bread;
}
public void run(){
for(int i=0;i<30;i++)
bread.eatBread();
}
}

public class BreadMain {
public static void main(String[] args) {
// bread를 공유하자
BreadPlate bread=new BreadPlate();
BreadMaker maker=new BreadMaker(bread);
BreadEater eater=new BreadEater(bread);
maker.setPriority(10);
eater.setPriority(1);
maker.start();
eater.start();
}
}
..^^ 2부에서~~