오늘은 자바 동시 프로그램을 살펴보고, 엔트리 프로그램을 작성하고, 스레드의 우선순위를 설정해봤습니다.
클래스 Elem은 Runnable을 구현합니다. void run(){ Thread.currentThread().setPriority(priority); int threadId = id++ while(cutDown--> 0){ double d = 1.2; while(d < 10000) d = d + (Math.E + Math.PI)/d; System.out.println("#" + threadId + "(" + cutDown + ") "); } }}public class Basic { public static void main(String args[]){ for(int i = 0; i < 10; i++){ Elem e = new Elem(); if(i == 0 ) e.setPriority(Thread.MAX_PRIORITY); else e.setPriority(Thread.MIN_PRIORITY); 스레드 t = new Thread(e) } }}
머신이 워낙 강력해서 처음에는 동시효과를 못느끼고 순차적으로 실행되는거 같아서 중간에 부동소수점연산을 추가해서 시간을 지연시켰습니다.
물론, Executor를 사용하여 주 함수의 스레드를 관리할 수 있습니다.
import java.util.concurrent.*;class Elem은 Runnable을 구현합니다. ){ return this.priority; } public void run(){ Thread.currentThread().setPriority(priority); id++; while(cutDown-- > 0){ double d = 1.2; while(d < 10000) d = d + (Math.E + Math.PI)/d; System.out.println("#" + threadId + "(" + cutDown + ")"); } }}public class Basic { public static void main(String args[]){// for(int i = 0; i < 10; i++){// Elem e = new Elem();// if(i == 0 )// e.setPriority(Thread.MAX_PRIORITY);// else// e.setPriority(Thread.MIN_PRIORITY);/ /Thread t = new Thread(e);// t.start();// } ExecutorService exec = Executors.newCachedThreadPool(); for(int i = 0; i < 10; i++){ Elem e = new Elem(); if(i == 0 ) e.setPriority(Thread.MAX_PRIORITY); .MIN_PRIORITY); exec.execute(e) } exec.shutdown();