[CS공부] Thread 구현 방법

탄니야·2024년 7월 19일

cs공부

목록 보기
6/8

스레드(Thread)란?

하나의 프로세스 안에서 독립적으로 실행되는 ‘작은 실행 단위’를 의미합니다.

프로세스(Process)란?

시스템에서 실행 중인 프로그램을 의미합니다.

java에서 Thread를 구현하는 방법

  1. Thread 클래스를 상속받아 run 메소드를 오버라이딩 하는 것
  2. Runnable 인터페이스를 implements 하여 run 메소드를 정의하는 것

[1.Tread 클래스 상속]

class Thread1 extends Thread{
	int num;

	public Thread1() {
		this.num = 0;
	}

	public Thread1(int num) {
		this.num = num;
	}

	@Override
	public void run() {
		System.out.println(this.num + " thread start");
		try{
			Thread.sleep(1000);
		}catch (InterruptedException e){
			e.printStackTrace();
		}
		System.out.println(this.num +" thread end");
	}
}

[2. Runnable 인터페이스 run 메소드 구현]

class Thread2 implements Runnable {
	int num;

	public Thread2() {
		this.num = 0;
	}

	public Thread2(int num) {
		this.num = num;
	}

	@Override
	public void run() {
		System.out.println(this.num + " thread start");
		try{
			Thread.sleep(1000);
		}catch (InterruptedException e){
			e.printStackTrace();
		}
		System.out.println(this.num +" thread end");
	}
}

[3. main 메소드에서 호출]

public class TestApplication {

	public static void main(String[] args) {
		Thread1 thread1 = new Thread1();
		thread1.start();
		System.out.println("main end");
	}

}

console 확인

profile
반갑습니다

0개의 댓글