쓰레드(Thread)는 컴퓨터의 CPU의 최소 사용단위 입니다.즉, 하나의 프로그램을 실행함에 있어 하나의 쓰레드를 사용하는 것이고 동시성을 통해 쓰레드를 동시에 사용하게 됩니다. 이를 '멀티 쓰레드'라고 합니다.
// 여러 작업을 동시에 수행하기 위해서 처리하는 클래스 java.lang.Thread
// 1) 수행할 내용을 public void run() 오버라이딩해서 작성한다
class PrintNumber extends Thread {
int count = 1;
// 저장 - 우클릭 - source - override/implement methods
@Override
public void run() {
for(int i = 1; i <= 25; i++) {
System.out.print(i + " ");
count++;
if (count % 5 == 0) {
System.out.println();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class PrintAlphabet extends Thread {
int count = 1;
@Override
public void run() {
for(char ch = 'a'; ch <= 'z'; ch++) {
System.out.print("알파벳 " + ch + " ");
count++;
if(count % 5 == 0) {
System.out.println();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Velog {
public static void main(String[] args) {
// 2) 동시 실행을 위해서는 객체의 start() 메서드로 호출하여 수행한다
Thread th1 = new PrintAlphabet();
Thread th2 = new PrintNumber();
th1.start();
th2.start();
}
}
<※ 결과는 다음과 같습니다.>
그 이유는 try/catch라는 구문을 통해 예외(Exception)처리를 해주었기 때문입니다.여기서 예외란 코드 수정에 따라 처리할 수 있는 문제점을 지칭하는 것으로 코드와 상관없이 발생하는 에러(Error)와는 차이가 있습니다.
그 중 try / catch는 직접적으로 해당 구문을 감싸서 예외처리를 해주는 방식입니다.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("예외 처리를 종료합니다.")
}
class PrintNumber extends Thread throws Exception{
@Override
public void run() {
for(int i = 1; i <= 10; i++) {
System.out.print(i + " ");
Thread.sleep(1000);
}
}
}
대신 예외 전가는 try/catch에 비해 구문의 가독성이 증가하게 되고 같은 예외를 처리하는 클래스를 기입해준다면 해당 예외를 한번에 처리할 수 있다는 차이점이자 큰 장점이 존재합니다.특히 예제에서 보여드린 Exception은 예외 클래스 중 최상위 클래스 이므로 모든 예외를 처리하고 상속을 통해 사용자의 자체적인 예외 클래스를 작성할 수 있도록 도와주게 됩니다.