먹었으면 뇌를 쓰자

내가 만든 코드~ 나를 위해 구웠지... (Thread 코드) 본문

JAVA/개념

내가 만든 코드~ 나를 위해 구웠지... (Thread 코드)

뇌이비 2022. 12. 18. 19:04

문제

쓰레드 적용해서 실행 시간 단축하기.

 

 

 

 

내 풀이(무려 정상 작동함)

 

 

import java.util.ArrayList;

class HeavyWork extends Thread{ // Thread 상속하기 
		
	String name;
	
	HeavyWork(String name){
		this.name=name;
	}

	public void run() {	 // 기존의 work() 메소드를 Thread의 run() 메소드로 변경하기
    	for (int i = 0; i < 5; i++) {
			try {
				Thread.sleep(100);
			} catch (Exception e) {
			}		
            }
		System.out.printf("%s done.\n",this.name);
	}
}


public class coding {	 
	public static void main(String[] args) {
		
		ArrayList<Thread> threads = new ArrayList<>();	// 쓰레드 담을 리스트 생성하기	
		long start = System.currentTimeMillis();
		
		for(int i=1; i<5; i++) { 		
			Thread t = new HeavyWork("w" + i); // HeavyWork 대신 Thread 객체 생성하기
			t.start(); // start() 메소드로 쓰레드 실행하기 	
			threads.add(t); // threads에 쓰레드 담기 
			
		}		
		for(int i=0;i<threads.size();i++) {
			Thread t = threads.get(i); // 쓰레드 담긴 threads 리스트를 Thread 객체에 담기 
			try {
				t.join(); // Thread가 모두 실행될 때까지 멈춤시키는 join() 메소드 실행
			} catch (Exception e) {
				
			}
		}		
		long end = System.currentTimeMillis();
		System.out.printf("elapsed time: %s ms\n",end-start);
	}
}
	
    
    
    
<console>
    
w3 done.
w1 done.
w2 done.
w4 done.
elapsed time: 554 ms // 2초에서 0.5초로 단축 성공!
Comments