본문 바로가기
Java

스레드 ( Thread )

by KDW999 2023. 1. 13.

Thread

ㅡ  프로세스에서 작업 수행 / 모든 프로세스에는 한 개 이상의 스레드가 존재

멀티 스레드 프로세스(multi-threaded process)  : 두 개 이상의 스레드로 작업을 수행하는 프로세스

 

*프로세스 → 실행 중인 프로그램 / 프로그램이 운영체제에 의해 메모리 공간을 할당받아 실행 중인 상태 / 프로세스는 데이터, 메모리 등의 자원과 스레드로 구성 

 

시간분할 방식 : 모든 프로세스에게 동일한 시간 할당

선점 방식 : 프로세스에게 우선 순위 부여 후 높은 순으로 진행

 

스레드 생성

ㅡ Thread 클래스 상속

ㅡ Runnable 인터페이스 구현

 

Thread 클래스 상속 / Runnable 인터페이스 구현

class Thread1 extends Thread {
   public void run() {
	   for(int i=0; i<10; i++) {
		   try {
			   System.out.print("#");
		} catch (Exception e) {
			System.out.println("오류요");
		}
	   }
	}
}

class Thread2 implements Runnable {
	
	public void run(){
		for(int i=0; i<10; i++) {
			   try {
				   System.out.print("@");
			} catch (Exception e) {
				System.out.println("오류요");
			}
		   }
	}
}
public class Test {

	public static void main(String[] args) {
           Thread1 th1 = new Thread1(); // Thread 클래스 상속
           
           Thread2 th2 = new Thread2(); // Runnable 인터페이스 구현
           Thread thrun = new Thread(th2); // 구현 클래스의 참조변수를 인자로 주고 인스턴스 생성
           
           th1.start();
           thrun.start();
		
	}
}

출력

Thread 클래스를 extends한 뒤 객체 생성 후 사용할 수 있다. 스레드는 start()로 시작

Runnable 인터페이스 구현은 구현한 클래스의 참조변수를 Thread 클래스 객채 생성 시 인자로 넣어준 후 사용할 수 있다.

* Runnable 인터페이스는 추상 메서드 run()를 가지고 있다.

 

Thread 클래스를 상속하면 다른 클래스는 상속할 수 없게 된다. / 인터페이스는 다중 상속

 

스레드는 너무 빨리 실행되서 출력 순서가 섞일 수 있다고 한다. → setPriority()로 우선 순위를 부여하거나 메서드 앞에 synchronized를 적어서 다른 스레드의 접근을 막고 먼저 작업을 진행 가능

synchronization : 스레드 간의 작업이 간섭되지 않게 막음 / 동기화

 

스레드 메서드 몇 개

Thread.sleep() ㅡ 지정 시간동안 block 상태 ( 잠깐 멈춤 ) / 1000이 1초 ex) sleep(2000)  / 이건 쓸려면 try catch문 사용

Thread.yiled() ㅡ 스레드가 자신의 시간을 다른 스레드에게 양보

참조변수.join() ㅡ 특정 스레드가 다른 스레드 작업 중 끼어들어 먼저 작업 수행 / 스레드들의 실행 순서 제어 시

this.wait() ㅡ 스레드 대기 / try catch문

this.notify() ㅡ 대기중인 스레드 깨움

Thread.currentThread().getName() ㅡ 현지 실행 중인 스레드 이름 반환

 

'Java' 카테고리의 다른 글

삼항 연산자  (0) 2023.01.17
제네릭 ( Generic )  (0) 2023.01.13
ArrayList  (0) 2023.01.12
컬렉션 프레임워크 ( Collection Framework ) / 제네릭 ( Generic )  (0) 2023.01.12
예외 처리 ( Exception Handling )  (0) 2023.01.11

댓글