본문 바로가기
CLASS/JAVA

#13-2 / Thread

by eungSe__ 2024. 5. 20.

 

✅ 웹개발자는 스레드 다룰 일이 크게 없다

-> web 개발자가 유일하게 스레드를 활용 하는 경우 : API Server

    Javascript에서 멀티 스레드(많이 써봣자 4개) : web worker을 쓰게 되면 멀티 스레드를 사용하게됨

⚡ 단일스레드(기존 알던방식)
단일스레드 : 순차적으로 실행되기 때문에 위에서 에러나면 아래도 실행안됨
public static void main(String[] args) {
    th1_box th = new th1_box();
    th.aaa();
    th.bbb(); //대기 

    int w=0;
    do {
        th1_box thb = new th1_box();
        thb.ccc(w); //애두 단일스레드
        w++;
    }while(w<21);

}

class th1_box{
	public void ccc(int z) {
		System.out.println("c:"+z);
	}
	
	
	public void aaa() {
		int w=0;
		do {
			System.out.println("a:"+w);
			w++;
		}while(w<21);
	}
	
	public void bbb() {
		int w=0;
		do {
			System.out.println("b:"+w);
			w++;
		}while(w<21);
	}
}

 

멀티 쓰레드 환경(class를 로드하여 출력하는 형태)

- .start();  : run 메소드를 호출해서 실행(start를 하면 run이 실행됨)
- Thread란 기본으로 1개의 쓰레드로만 작동한다.
Thread 클래스를 해당 클래스로 상속시킨 후 Thread를 선언하여 start메소드 활용 시 멀티 쓰레드로 작업 환경이 변경됩니다. 단,웹기본속성은 단일 쓰레드이다.
- run 메소드에 코드 작성시 결과값은 다르게 출력된다.

Thread 스레드변수명 = new Thread(클래스 변수명);
스레드변수명 .start()

run() : run 메소드에 코드 작성시 결과값은 다르게 출력된다.

package oop2;
public class th1 {
	public static void main(String[] args) {
		//멀티 스레드 호출 및 코드 방식
		int w=0;
		do {
			th2_box thb2 = new th2_box(w);
			//thb2.zzz(w); //애두 단일스레드 => 순차적으로 출력
			Thread th = new Thread(thb2);
			th.start(); //run 메소드를 호출해서 실행(start를 하면 run이 실행됨)
			w++;
		}while(w<21);
	}

}

class th2_box extends Thread{
	int no = 0;
	public th2_box(int n) { //즉시실행
		this.no = n;
	}
	
	public void zzz(int n) { //멀티스레드 미적용
		System.out.println("zzz:"+n);
	}
	
	@Override
	public void run() { //멀티쓰레드 클래스를 적용한 메소드
		System.out.println(this.no); //완전 뒤죽박죽 출력 : 먼저 처리된게 먼저 출력
		//super.run();
	}
}

 

⚡ 멀티쓰레드 (interface) 활용

interface도 동일하게 Thread 호출
run 메소드에 코드 작성시 결과값은 다르게 출력된다.
Thread.sleep(시간) : 몇초 후 실행 - ❗ 예외처리 필수

package oop2;
//멀티쓰레드 (interface) 활용
public class th2 {

	public static void main(String[] args) {
		for(int f=0; f<100; f++) {
			th2_class th = new th2_class();
			th.abc(f);
			Thread tr = new Thread(th); //interface도 동일하게 Thread 호출
			//tr.start();
			
			//여기선 1초에 한번씩 실행
			//(반복문 안에 들어있어서 각 작업별로 Thread가 휴식기 및 별개로 작업이 이루어짐)
			try {
				tr.sleep(1000);	
				tr.start();	
			}catch(Exception e) {
				System.out.println("문제발생!");
			}
			
		}
	}
}

//interface Thread (Runnable) 활용하며 run 작동
class th2_class implements Runnable{
	int n=0;
	public void abc(int z) {
		this.n = z;
	}
	
	@Override
	public void run() { //run 메소드에 코드 작성시 결과값은 다르게 출력된다.
		try {
			//Thread.sleep(5000); //5초뒤 작동 , Thread.sleep : 휴식기(시간)	
		}catch(Exception e) {
			System.out.println("Thread 오류 발생");
		}
		
		System.out.println(this.n); //뒤죽박죽 출력
		
	}
}

 

⚡ 응용
package oop2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//멀티스레드 응용편
public class th3 {
/*
 [응용문제]
 Thread를 이용하여 각각의 배열의 값을 모두 더하는 결과를 출력하는 프로세서를 제작하시오.
 */
	public static void main(String[] args) {
		Integer data1[] = {10,20,30,40,50,60,70,80,90};
		Integer data2[] = {5,10,15,20,25,30,35,40,45};
		Integer data3[] = {7,14,21,28,35,42,49,56,63};
		
		th3_box th3_1 = new th3_box(data1);
		Thread tr_1 = new Thread(th3_1);
		tr_1.start();
		
		th3_box th3_2 = new th3_box(data2);
		Thread tr_2 = new Thread(th3_2);
		tr_2.start();
		
		th3_box th3_3 = new th3_box(data3);
		Thread tr_3 = new Thread(th3_3);
		tr_3.start();
	}
}

class th3_box extends Thread{
	int sum = 0;
	ArrayList<Integer> all = null;
	
	public th3_box(Integer z[]) {
		this.all = new ArrayList<Integer>(Arrays.asList(z));
		int f;
		for(f=0; f<this.all.size(); f++) {
			sum += this.all.get(f);
		}
	}
	
	@Override
	public void run() {
		System.out.println(sum);
		
		super.run();
	}
}

 

'CLASS > JAVA' 카테고리의 다른 글

#13-4 / I/O 🔥  (0) 2024.05.20
#13-3 / Map클래스배열(Key배열)  (0) 2024.05.20
#13-1 / String, StringBuilder, StringBuffer  (0) 2024.05.20
#12 / remind2  (0) 2024.05.17
#11-2 / 배열을 이용한 예외처리  (0) 2024.05.16