본문 바로가기
자바과정/Java

Java 기초 - 11일차

by Parkej 2021. 2. 19.

스레드 & 익셉션

Thread & Exception

 

 

// 스레드

- 동기화 (기아 공정 교착상태)에 대해

교육 자료

- 메모리를 할당받아 실행 중인 프로그램을 프로세스라고 합니다.

- 프로세스 내의 명령어 블록으로 시작점과 종료점을 가진다.

- 실행중에 멈출 수 있으며 동시에 수행 가능하다.

어떠한 프로그램내에서 특히 프로세스 내에서 실행되는 흐름의 단위.

package threadT;

public class SingleThreadEx implements Runnable{//extends Thread{
	private int[] temp;
	public SingleThreadEx() {
		temp = new int[10];
		for(int i=0;i<temp.length;i++) {
			temp[i] = i;
			// i = start
		}
		
	}
	public void run() {
		for(int start:temp) {
			try {
				Thread.sleep(1000);
			}catch(InterruptedException ie) {
				ie.printStackTrace();
			}
		System.out.printf("스레드 이름 : %s ,", Thread.currentThread().getName());
		System.out.printf("temp value : %d \n", start);
		}
	}
	public static void main(String[] args) {
		SingleThreadEx st = new SingleThreadEx();
		Thread t = new Thread(st, "Threadnamed");
		t.start();
	}
}

 

 

// 조인사용

- join() 메서드는 join() 메서드를 호출한 스레드가 종료할 때까지 종료할 때까지 현재의 스레드를 기다리게 된다.

 

package threadT;

class MyRunnableTwo implements Runnable{

	@Override
	public void run() {
		System.out.println("run");
		first();
	}

	public void first() {
		System.out.println("first");
		second();
	}
	public void second() {
		System.out.println("second");
	}
}

public class JoinEx {
	public static void main(String[] args) {
		System.out.println(Thread.currentThread().getName()+" start");
		MyRunnableTwo mt = new MyRunnableTwo();
		Thread t = new Thread(mt);
		t.start();
		try {
			t.join();
		}catch(InterruptedException ie) {
			ie.printStackTrace();
		}
		
		System.out.println(Thread.currentThread().getName()+" end");
	}


---- 출력 ----
main start
run
first
second
main end

 

// ATM 실습

- wait와 notify는 동기화된 블록안에서 사용해야 한다. wait를 만나게 되면 해당 쓰레드는 해당 객체의 모니터링 락에 대한 권한을 가지고 있다면 모니터링 락의 권한을 놓고 대기한다.

- 경우에 따라 두 스레드가 교대로 번갈아가며 실행해야 할 경우가 있다. (정확한 교대작업이 필요한 경우, 한 스레드가 작업이 끝나며 상대방 스레드의 일시정지를 풀어주고 자신은 일시정지로 만들어야 한다.)

공유객체 를 사용하여 두 스레드가 작업할 내용을 각각 동기화 메소드로 구분해 놓은 후 한 스레드가 작업이 완료되면 notify()메서드를 호출한다.

notify() => 일시 정지 상태에 있는 다른 스레드를 실행 대기 상태로 만듬

wait() => 스레드를 일시 정지 상태로 만듬

위 두 메서드는 Thread 클래스가 아닌 Object 클래스에 선언된 메소드이므로 모든 공유 객체에서 호출이 가능하다. (동기화블록에서만 사용 가능)

package threadT;

public class ATM implements Runnable{
	private long depositeMoney = 10000;
	@Override
	public void run() {
		synchronized(this){
			for(int i=0;i<10;i++) {
				try {
//					notifyAll();
					Thread.sleep(1000);
//					wait();

				}catch(InterruptedException ie) {
					ie.printStackTrace();
				}
				if(getDepositeMoney() <= 0) {
					break;
				}
				this.notify();
				withDraw(1000);
				try {
					this.wait();
				}catch(InterruptedException ie) {
					ie.printStackTrace();
				}
			}
		}
	}

	private void withDraw(long howMuch) {
		if(getDepositeMoney() > 0) {
			depositeMoney -= howMuch;
			System.out.print(Thread.currentThread().getName()+" , ");
			System.out.printf("잔액 : %,d 원 \n", getDepositeMoney());
		}
		else {
			System.out.print(Thread.currentThread().getName()+" , ");
			System.out.println("잔액이부족합니다");		
		}
	}

	public long getDepositeMoney() {
		return depositeMoney;
	}

	public static void main(String[] args) {
		ATM atm = new ATM();
		Thread mother = new Thread(atm, "mother");
		Thread son = new Thread(atm, "son");
		son.start();
		mother.start();
		//		synchronized(mother) {
		//			try {
		//				mother.wait();
		//			}catch (InterruptedException e) {
		//				e.printStackTrace();
		//			}
		//		}
	}
}

 

------ Exception

 

에러와 예외차이
   Error(에러)와 Exception(예외의 차이) 
- 에러(Error)란 컴퓨터 하드웨어의 오동작 또는 고장으로 인해 응용프로그램에 이상이 생겼거나 JVM 실행에 문제가 생겼을 경우 발생하는것을 말합니다. 이 경우 개발자는 대처할 방법이 극히 제한적입니다. 하지만 예외(Exception)은 다릅니다. 예외란 사용자의 잘못된 조작 또는 개발자의 잘못된 코딩으로 인해 발생하는 프로그램 오류를 말합니다. 예외가 발생하면 프로그램이 종료가 된다는것은 에러와 동일하지만 예외는 예외처리(Exception Handling)을 통해 프로그램을 종료 되지 않고 정상적으로 작동되게 만들어줄 수 있습니다. 자바에서 예외처리는 Try Catch문을 통해 해줄 수 있습니다.

- 문제가 발생하게끔 끝까지 동작하게끔 하는게 예외처리

 

package exception;

public class ExceptionEx1 {

	public static void main(String[] args) {
		int[] var = { 1, 2, 3 };
		for (int i = 0; i <= 3; i++) {
			try {
				System.out.println("var[" + i + "] : " + var[i]);
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("예외발생");
			}
		}
		System.out.println("끝");
	}
}



package exception;

import java.util.*;

public class ExceptionEx3 {

	public static void main(String[] args) {
		int var = 50;
		try {
			System.out.print("정수 입력 : ");
			int data = new Scanner(System.in).nextInt();
			System.out.println(var / data);
		} catch (InputMismatchException ie) {
			System.out.println("정수가 아닙니다.");
		} catch (NumberFormatException ne) {
			System.out.println("숫자가 아닙니다.");
		} catch (ArithmeticException ie) {
			System.out.println("0으로 나눌수 없다.");
		} catch (Exception e) {
			System.out.println("난 부모.");
		}
		System.out.println("끝");
	}

}

 

// Finally

 

package exception;

public class FinallyEx1 {

	public static void main(String[] args) {
		int[] var = {1,2,3};
		
		for(int i=0;i<=3;i++) {
			try {
			System.out.println((i+1)+"번째");
			System.out.println("var ["+i+"] : "+var[i]);
			System.out.println("----------------------");
			}catch(Exception e){
				System.out.println("배열 넘음");
				return;
			}finally {
				System.out.println("Finally 출력");
			}
			System.out.println("끝");
		}
	}
}

 

// Throws

 

package exception;

public class ThrowsEx1 {

	public void setData(String n) throws NumberFormatException{
		if(n.length() >= 1) {
			String str = n.substring(0,1);
			printData(str);
		}
	}
	
	private void printData(String n) throws NumberFormatException {
		int dan = Integer.parseInt(n);
		System.out.println(dan + "단");
		System.out.println("------------");
		for(int i=0;i<9;i++) {
			System.out.println(dan + "*"+(i+1)+"="+(dan*(i+1)));
		}
	}
	
	public static void main(String[] args) {
		ThrowsEx1 t1 = new ThrowsEx1();
		try {
			t1.setData(args[0]);
		}catch(Exception e){
			System.out.println("첫문자가 숫자가 아님");
		}
	}

}

 

 

참고 사이트 :

blog.cornsworld.co.kr/189

programmers.co.kr/learn/courses/9/lessons/278

 

 

반응형

댓글