시작하며
여러분 안녕하세요!
DreamHanks의 254cm입니다.
이번 시간에는 Thread에 대해 설명할 것입니다.
Java의 전체 기사는 여기를 클릭해 주세요.
이전 기사는 [Java 개발] 제29회 익명의 내부 클래스에 대해서 배워 봤습니다.
Thread이란?
스레드(Thread)는 자바 프로그램으로 작업을 처리하는 것이며, 모든 자바 프로그램은 한 개 이상의 스레드를 가지고 있습니다.
스레드는 한 가지 작업을 맡아 처리합니다. 즉, 여러 스레드가 존재하면 여러 작업을 동시에 처리할 수 있습니다.
main() 메서드가 기본으로 제공되는 스레드이며, main() 이외의 스레드를 만들기 위해서는 Thread 클래스를 상속받거나, Runnable 인터페이스를 구현합니다.
둘 이상의 쓰레드를 운용하고 있는 것을 Multithreading이라고 부릅니다.
Thread 사용법
샘플 1
1 2 3 4 5 6 7 8 9 10 11 |
public class ThreadSample extends Thread{ public static void main(String[] args) { ThreadSample tSample = new ThreadSample(); tSample.start(); } public void run() { System.out.println("Excute run method"); } } |
기본적인 사용법은 스레드를 사용하고 싶은 클래스에서 Thread 클래스를 상속받아서
스레드가 처리할 작업을 run메서드에 만듭니다.
그리고 Thread 객체의 인스턴스를 생성하고 start 메서드를 사용합니다.
스레드의 start 메소드는 run 메소드를 실행하는 것으로 설계되어 있습니다.
실행 결과
1 |
Excute run method |
샘플 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package practiceProject; public class ThreadSample extends Thread{ public static void main(String[] args) { ThreadSample thread1 = new ThreadSample(); ThreadSample thread2 = new ThreadSample(); thread1.start(); thread2.start(); System.out.println("main method end"); } public void run() { for(int i = 0; i < 10; i++) { System.out.println(getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
위의 샘플은 두 가지 스레드를 생성하여 처리합니다.
Thread.sleep() 메서드는 메서드의 실행을 인수만큼 멈추는 메서드입니다.
getName메서드는 현재 수행중인 스레드의 이름을 반환하는 메서드입니다.
위의 샘플을 실행해보면
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
main method end Thread-1 Thread-0 Thread-0 Thread-1 Thread-0 Thread-1 Thread-1 Thread-0 Thread-1 Thread-0 Thread-0 Thread-1 Thread-0 Thread-1 Thread-1 Thread-0 Thread-0 Thread-1 Thread-0 Thread-1 |
와 같이 됩니다.
두 쓰레드의 처리가 끝나기 전에 main 메서드가 종료됩니다.
만약 main 메서드가 쓰레드로 처리된 값을 받아 수행해야 하는 작업이 있다면
쓰레드가 종료되기 전에 main 메서드가 종료되어 오류가 발생합니다.
샘플 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public class ThreadSample extends Thread{ public static void main(String[] args) { ThreadSample thread1 = new ThreadSample(); ThreadSample thread2 = new ThreadSample(); thread1.start(); try { thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } thread2.start(); try { thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main method end"); } public void run() { for(int i = 0; i < 5; i++) { System.out.println(getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
위와 같이 join 메소드를 사용하면 join 메소드를 호출한 쓰레드가 종료될 때까지
다음 동작을 수행하지 않습니다.
실행 결과
1 2 3 4 5 6 7 8 9 10 11 |
Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 main method end |
샘플 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class ThreadSample implements Runnable{ public static void main(String[] args) { Thread th = new Thread(new ThreadSample()); th.start(); } @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()); } } } |
Runnable 인터페이스를 상속받아 쓰레드를 사용하는 샘플입니다.
Thread 클래스를 상속받는 것과 큰 차이는 없지만,
run 메서드의 오버라이드를 강제할 수 있는 장점이 있습니다.
실행 결과
1 2 3 4 5 |
Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 |
Thread 우선 순위
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class ThreadSample extends Thread{ public static void main(String[] args) { ThreadSample th0 = new ThreadSample(); ThreadSample th1 = new ThreadSample(); ThreadSample th2 = new ThreadSample(); ThreadSample th3 = new ThreadSample(); th0.setPriority(MIN_PRIORITY); th1.setPriority(MAX_PRIORITY); th2.setPriority(MIN_PRIORITY); th3.setPriority(MIN_PRIORITY); System.out.println(th0.getPriority()); System.out.println(th1.getPriority()); System.out.println(th2.getPriority()); System.out.println(th3.getPriority()); th0.start(); th1.start(); th2.start(); th3.start(); } public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
스레드는 우선순위를 나타내는 필드를 가지고 있습니다. 그 필드를 조작함으로써 각 스레드 처리의 우선순위를 결정할 수 있습니다.
우선순위에 따라 해당 쓰레드는 더 많은 시간에 처리할 수 있습니다.
getPriority와 setPriority 메서드를 이용해 우선순위의 필드를 조작할 수 있습니다.
우선순위가 높을수록 더 많은 시간에 처리를 하며 우선순위의 범위는 1부터 10까지입니다.
실행 결과
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
1 10 1 1 Thread-0 Thread-1 Thread-2 Thread-3 Thread-1 Thread-2 Thread-0 Thread-3 Thread-1 Thread-3 Thread-2 Thread-0 Thread-1 Thread-0 Thread-3 Thread-2 Thread-3 Thread-2 Thread-0 Thread-1 |
끝으로
이번 기사는 이상입니다.
방문해 주셔서 감사합니다.
コメント