스레드(Thread) 기본 실습 -blocking 메소드(SleepTest, yield, join)
SleepTest 실습
public class GooGoo implements Runnable {
private int dan;
public GooGoo(int dan) {
this.dan = dan;
}
@Override
public void run() {
long sleeptime = (long)(Math.random() * 500);
System.out.println(dan + " 단이 " + sleeptime + "만큼 sleep");
try {
Thread.sleep(sleeptime); //이 구문이 없을 경우 스레드의 순서가 뒤죽박죽이 됨
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i = 1 ; i <=9 ; i++ ){
System.out.println(dan + " X " + i + " = " + (dan * i) );
}
}
}
//스레드 SleepTest public class SleepTest { public static void main(String[] args) { for(int i = 1 ; i <= 50 ; i++){ try { Thread.sleep(1000); //1초씩 딜레이를 줌 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(i); } } }
yield 실습
public class GooGoo implements Runnable {
private int dan;
public GooGoo(int dan) {
this.dan = dan;
}
@Override
public void run() {
if(dan == 8){
System.out.println("8단이 yield됨");
Thread.yield();
}
for(int i = 1 ; i <=9 ; i++){
System.out.println(dan + "X" + i + " : " + (dan * i));
}
}
}
//yield 실습
public class Ex12_06 {
public static void main(String[] args) {
Thread t2 = new Thread(new GooGoo(2));
Thread t3 = new Thread(new GooGoo(3));
Thread t4 = new Thread(new GooGoo(4));
Thread t5 = new Thread(new GooGoo(5));
Thread t6 = new Thread(new GooGoo(6));
Thread t7 = new Thread(new GooGoo(7));
Thread t8 = new Thread(new GooGoo(8));
Thread t9 = new Thread(new GooGoo(9));
t2.setPriority(4);
t3.setPriority(4);
t4.setPriority(4);
t5.setPriority(4);
t6.setPriority(6);
t7.setPriority(5);
t8.setPriority(5);
t9.setPriority(5);
//동등한 우선권를 가진 8단과 9단
//8단이 yield 메소드를 만나서 우선권을 넘긴다. (단 반드시 9단에게 넘어가지는 않는다)
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
System.out.println("main() 종료....");
}
}
join 실습
public class GooGoo implements Runnable {
private int dan;
public GooGoo(int dan) {
this.dan = dan;
}
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
for(int i = 1 ; i <=9 ; i++){
System.out.println(dan + "X" + i + " : " + (dan * i));
}
}
}
//join 실습
public class Ex12_07 {
public static void main(String[] args) {
Thread t2 = new Thread(new GooGoo(2));
Thread t3 = new Thread(new GooGoo(3));
Thread t4 = new Thread(new GooGoo(4));
Thread t5 = new Thread(new GooGoo(5));
Thread t6 = new Thread(new GooGoo(6));
Thread t7 = new Thread(new GooGoo(7));
Thread t8 = new Thread(new GooGoo(8));
Thread t9 = new Thread(new GooGoo(9));
t2.setPriority(4);
t3.setPriority(4);
t4.setPriority(4);
t5.setPriority(4);
t6.setPriority(4);
t7.setPriority(4);
t8.setPriority(4);
t9.setPriority(4);
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
try {
t5.join();
//5단이 실행될때 join되어 스레드가 종료하기까지 Main스레드가 block된다.
} catch (InterruptedException e) {
}
System.out.println("main() 종료....");
}
}