멀티스레드 (Multi Thread)

losuif·2021년 8월 6일
0
post-thumbnail

👩🏼‍💻 멀티스레드 (Multi Thread)


  • 특정 메서드가 실행되고 종료되기 전 다른 메서드가 실행되는 것

  • 전기 신호 대기 장소(스택, 힙) -> CPU에서 전달받은 후 CPU 처리 단계에 따라 순서대로 실행, 실행결과도 순서대로 RAM에 재저장 : 이 때 각 프로그램에는 실행 시작과 끝이 있는데, 이 중간에 다른 프로그램이 실행되지 못한다면 싱글스레드 프로그램 / 하나의 프로그램이 실행되고 끝나기 전 다른 프로그램이 실행된다면 멀티스레드 프로그램

  • 멀티스레드를 구현하기 위해서는 2개 이상의 클래스가 필요하다
    : 메인클래스 + Thread 클래스 상속받은 커스텀클래스 or Runnable 인터페이스 구현한 커스텀클래스 + .....
    (메인클래스가 아닌 커스텀클래스에 멀티스레드를 하도록 기능을 주는것)

  • run()메서드를 사용하여 멀티스레드 구현

  • 메인클래스에서 객체로 생성된 커스텀 클래스
    객체변수.start() 메서드 실행
    → 커스텀 클래스의 run()메서드의 내용이 멀티스레드로 실행

  • 멀티스레드 딜레이 : 컴퓨터 시스템에 따라 처리속도가 다르므로 멀티스레드가 구현되었으나 결가는 싱글스레드가 구현된 것 처럼 나타날 수 있는데, 이런 현상을 해결하기 위해 사용한다.
    => Thread.sleep(ms); (ms = 1/1000초)
    => ChckedException, 반드시 try-catch문 사용, InterruptedException으로 예외처리



Thread 클래스 상속 멀티스레드


메인클래스)

import java.util.Scanner;

public class MultiThreadTest1 {

	public static void main(String[] args) {

		System.out.println("알파벳과 숫자의 멀티스레드 출력");
		
		Scanner scanner = new Scanner(System.in);
		System.out.print("\n출력하실 숫자 범위를 입력하세요 "
				+ "(10~20 사이에서 입력)): ");
		int num = scanner.nextInt();
		scanner.close();
		System.out.println();
		
		System.out.print("처리중입니다");
		for (int i = 0; i <= 4; i++) {
			try {	
				Thread.sleep(800);
				System.out.print(".");
				if (i == 4) {
					System.out.println();
					break;
				}
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		
		CountThread countThread = new CountThread(num);
		countThread.start(); // start메서드 사용 => 멀티스레드 구현
				     // Thread클래스의 메서드 => 인터페이스로 구현하면 오류
		for (char ch = 'A'; ch <= 'Z'; ch++) {
			try{
	            Thread.sleep(3);
	            if (ch == 'L') System.out.println();
	            System.out.print(ch);
	        }catch(InterruptedException e){
	            System.out.println(e.getMessage());
	        }
	
			
		} //메인클래스에서 별도로 실행되는 프로그램
       }
 }

커스텀클래스)
public class CountThread extends Thread{
					//Thread는 내장클래스
	
	private int num;
	public CountThread(int num) {
			this.num = num;
					}

	@Override
	public void run() {
		for (int i = 0; i <= num; i++) {
			
			 try{
		            Thread.sleep(3);
		            System.out.print(i);
                    
		        }catch(InterruptedException e){
		            System.out.println(Thread.currentThread().getName());
		        }
		
	} //커스엄메서드에서 구현하려고 했던 내용
	  //멀티스레드에 만들고싶은 내용을  
	  //run 메서드 안에 넣어 오버라이딩

	}
}



Runnable 인터페이스 구현 멀티스레드


메인클래스)

public static void main(String[] args) {

		CountThread countThread = new CountThread();
		Thread thread = new Thread(countThread);
					//생성자매개변수의 인수

		thread.start(); 

		for (char ch = 'A'; ch <= 'Z'; ch++) {
			try{
	            Thread.sleep(1000L);
	            System.out.print(ch);
	        }catch(InterruptedException e){
	            System.out.println(e.getMessage());
	        }
			
	}
  }

커스텀클래스)
public class CountThread implements Runnable{

@Override
	public void run() {
		for (int i = 0; i < 30; i++) {
			 try{
		            Thread.sleep(1000);
		            System.out.print(i);
		        }catch(InterruptedException e){
		            System.out.println(e.getMessage());
		        }
		
	}
}

0개의 댓글