본문 바로가기

콩's EDUCATION/콩's JAVA_RUN

synchronized 연습

thread 연습


 

class Account {
 String name;
 int total;

 public Account(String name) {
  this.name = name;
 }
 // 순서 스레드 접근 영역 : 동기화 영역.
 synchronized void deposit(int money, String loc) {
  total += money;
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(loc+money+total);
 }

 int getTotal() {
  return total;
 }
}
class Bank extends Thread{
 Account acc; // 계좌 이름
 int money; // 입금액
 String loc; //지점이름
  
 public Bank(Account acc, int money, String loc) {
  this.acc = acc;
  this.money = money;
  this.loc = loc;
 }

 @Override
 public void run() {
  acc.deposit(money, loc);
 }
 
}

public class AccountTest {
 public static void main(String[] args) {
  Account a1 = new Account("내 계좌");
  Bank b1 = new Bank(a1,1000,"강남은행");
  Bank b2 = new Bank(a1,2000,"광주은행");
  Bank b3 = new Bank(a1,3000,"대구은행");
  Bank b4 = new Bank(a1,4000,"부산은행");
  
  b1.start();
  b2.start();
  b3.start();
  b4.start();  
 }
}

 


 

AccountTest.java