20220825
한 번에 끝내는 Java/Spring 웹 개발 마스터
1) Thread 우선순위
package ch21;
class PriorityThread extends Thread {
public void run() {
int sum = 0;
Thread t = Thread.currentThread();
System.out.println(t + "start");
for (int i = 0; i <= 1000000; i++) {
sum += i;
}
System.out.println(t.getPriority() + "end");
}
}
public class PriorityTest {
public static void main(String[] args) {
int i;
PriorityThread pt1 = new PriorityThread();
PriorityThread pt2 = new PriorityThread();
PriorityThread pt3 = new PriorityThread();
pt1.setPriority(Thread.MIN_PRIORITY);
pt1.setPriority(Thread.NORM_PRIORITY);
pt1.setPriority(Thread.MAX_PRIORITY);
pt1.start();
pt2.start();
pt3.start();
}
}
- 우선 순위가 높은 Thread가 CPU의 배분을 받을 확률이 높다
- Thread.MIN_PRIORITY(=1) ~ Thread.MAX_PRIORITY(=10)
2) join()
package ch21;
public class JoinTest extends Thread {
int start;
int end;
int total = 0;
public JoinTest(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
int i;
for(i=start; i<=end; i++) {
total += i;
}
}
public static void main(String[] args) {
JoinTest join1 = new JoinTest(1, 50);
JoinTest join2 = new JoinTest(51, 100);
join1.start();
join2.start();
try{
join1.join();
join2.join();
}catch (InterruptedException e) {
System.out.println(e);
}
int lastTotal = join1.total + join2.total;
System.out.println("join1.total = " + join1.total);
System.out.println("join2.total = " +join2.total);
System.out.println("lastTotal = " + lastTotal);
}
}
- 동시에 두 개 이상의 Thread가 실행 될 때 다른 Thread의 결과를 참조 하여 실행해야 하는 경우 join() 함수를 사용