2023-02-27 월 / JAVA

권혁현·2023년 2월 27일
0

Java

목록 보기
43/44
post-thumbnail

1. 아래의 네트웍 객체에 대하여 설명하시오.

  • URLConnection
    추상클래스로 URL객체로부터 생성 됨
    URL클래스의 openConnection()메소드를 이용
  • InetAdrress
    호스트의 IP주소를 비롯한 네트워크상의 정보를 얻어오는 클래스
  • Socket
    네트워크상에서 서로 다른 호스트 사이의 통신을 위한 수단
  • SeverSocket
    서버와 클라이언트 사이의 Socket 및 I/O Stream 연결을 통한 통신

2. 아래를 실행보고, balance 가 마이너스 금액이 찍히는 이유를 적고 코드를 수정해 보시오.

class Ex13_12 {
	public static void main(String args[]) {
		Runnable r = new RunnableEx12();
		new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
		new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
	}
}

class Account {
	private int balance = 1000;

	public  int getBalance() {
		return balance;
	}

	public void withdraw(int money){
		if(balance >= money) {
			try { Thread.sleep(1000);} catch(InterruptedException e) {}
			balance -= money;
		}
	} // withdraw
}

class RunnableEx12 implements Runnable {
	Account acc = new Account();

	public void run() {
		while(acc.getBalance() > 0) {
			// 100, 200, 300중의 한 값을 임으로 선택해서 출금(withdraw)
			int money = (int)(Math.random() * 3 + 1) * 100;
			acc.withdraw(money);
			System.out.println("balance:"+acc.getBalance());
		}
	} // run()
}

  • 동기화가 안되어 있어서 public void withdraw(int money) 함수를 실행중에 다른 함수가 쓰레드를 가로채가서 생기는 문제.

  • public void withdraw(int money) 앞에 synchronized 를 붙인다.

class Ex13_12 {
	public static void main(String args[]) {
		Runnable r = new RunnableEx12();
		new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
		new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
	}
}

class Account {
	private int balance = 1000;

	public  int getBalance() {
		return balance;
	}

	synchronized public void withdraw(int money){
		if(balance >= money) {
			try { Thread.sleep(1000);} catch(InterruptedException e) {}
			balance -= money;
		}
	} // withdraw
}

class RunnableEx12 implements Runnable {
	Account acc = new Account();

	public void run() {
		while(acc.getBalance() > 0) {
			// 100, 200, 300중의 한 값을 임으로 선택해서 출금(withdraw)
			int money = (int)(Math.random() * 3 + 1) * 100;
			acc.withdraw(money);
			System.out.println("balance:"+acc.getBalance());
		}
	} // run()
}

0개의 댓글