-
[java] Thread / Runnablejava 2023. 1. 20. 16:14
동작하고 있는 프로그램을 process라고한다.
보통 한개의 프로세스는 한가지일을 하지만
쓰레드를 이용하면 한 프로세스 내에서 두가지 또는 그 이상의 일을 동시에 할 수 있다.쓰레드가 하나인경우
public class Sample extends Thread{ public void run(){ System.out.println("thread run"); } public static void main(String[] args){ Sample sample = new Sample(); sample.start(); //thread run출력 } }
Thread클래스를 상속했다. Thread클래스는 start실행시 run메소드가 수행되게끔 내부적으로 설계되어있다.
쓰레드가 여러개인경우
public class Sample extends Thread{ int seq; public Sample(int seq){ this.seq = seq; } public void run(){ System.out.println(this.seq+ " thread start"); try{ Thread.sleep(1000); //1초 대기한다. }catch(Exception e){ } System.out.println(this.seq + "thread end"); } public static void main(String[] args){ for (int i = 0; i < 10; i++) { Thread t = new Sample(i); t.start(); } System.out.println("main end"); } }
5 thread start 3 thread start 0 thread start 6 thread start 4 thread start 1 thread start 2 thread start main end 9 thread start 7 thread start 8 thread start 5thread end 0thread end 3thread end 8thread end 1thread end 6thread end 4thread end 9thread end 2thread end 7thread end
- 출력을 해보면 0번부터 9번쓰레드까지 순서대로 실행되지않고 순서가 일정하지 않은것을 알 수 있다.
-> 쓰레드는 순서에 상관없이 동시에 실행된다.
- 쓰레드가 종료되기 전에 main메소드가 종료된다.
Join
모든 쓰레드가 종료된 후에 main메소드를 종료시키고 싶은경우?
쓰레드의 join메소드는 쓰레드가 종료될때까지 기다리게 하는 메소드이다.
쓰레드 프로그래밍시, 꼭 쓰레드가 종료된 후 그다음 로직을 수행해야한다. 종료된걸 확인하기 위해 join메소드를 사용한다.
import java.util.ArrayList; public class Sample extends Thread{ int seq; public Sample(int seq){ this.seq = seq; } public void run(){ System.out.println(this.seq+ " thread start"); try{ Thread.sleep(1000); //1초 대기한다. }catch(Exception e){ } System.out.println(this.seq + "thread end"); } public static void main(String[] args){ ArrayList<Thread> threads = new ArrayList<>(); //threads이름의 배열 생성 for (int i = 0; i < 10; i++) { Thread t = new Sample(i); //쓰레드 0부터9까지 생성 t.start(); //생성후 run돌림 threads.add(t); //쓰레드를 배열에 저장 } for (int i = 0; i < threads.size(); i++) { Thread t = threads.get(i); //threads의 해당 인덱스 내부 값(쓰레드 들)을 가져와서 t 쓰레드변수에 저장함 try { t.join();//threads에 담긴 각각의 thread에 join메소드를 호출해 쓰레드가 종료될떄까지 기다리게함 } catch (Exception e) { } } System.out.println("main end"); } }
Runnable
쓰레드 객체를 만들때 위 예처럼 Thread클래스를 상속하여 만들곤 하지만, Thread클래스를 상속하면 다중상속이 안되기때문에 다른 클래스를 상속할 수 없다.
그래서 보통은 Runnable인터페이스를 구현하도록 하는 방법을 주로사용한다.
import java.util.ArrayList; public class Sample implements Runnable{ int seq; public Sample(int seq){ this.seq = seq; } public void run(){ System.out.println(this.seq+ " thread start"); try{ Thread.sleep(1000); }catch(Exception e){ } System.out.println(this.seq + "thread end"); } public static void main(String[] args){ ArrayList<Thread> threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Sample(i)); //Thread의 생성자로 Runnable인터페이스를 구현한 객체를 넘긴다. t.start(); threads.add(t); } for (int i = 0; i < threads.size(); i++) { Thread t = threads.get(i); try { t.join(); } catch (Exception e) { } } System.out.println("main end"); } }
'java' 카테고리의 다른 글
4장 연습문제 (0) 2023.01.22 [java] 함수형 프로그래밍 (람다, 스트림) (0) 2023.01.20 [java] 예외처리 (Exception), 트랜잭션 (0) 2023.01.20 [java] this, static, 싱글톤, final, 상수 (0) 2023.01.19 [java] 패키지와 접근제한자(public,protected/default/private) (0) 2023.01.19