JAVA Basic 강의자료] Interrupt을 이용한 쓰레드 종료 예제

 

JAVA Basic 강의자료] Interrupt을 이용한 쓰레드 종료 예제

 

 

 

 

실무개발자를위한 실무교육 전문교육센터학원
www.oraclejava.co.kr에 오시면 보다 다양한 강좌를 보실 수 있습니다.

 

 

 

Interrupt을 이용한 쓰레드 종료 예제

 

 

<소스코드>

 

class InterruptTest extends Thread {
   
    public void run() {
        for( int i = 0; i < count; i++ )
            System.out.println( i+1 + ". before sleep..." );

        try {
            sleep(500);
        } catch( InterruptedException e ) {
            System.out.println( "InterruptedException" );
        }
    }

    static int count;

    public static void main(String[] args) {
        count = Integer.parseInt(args[0]);
        InterruptTest thr = new InterruptTest();
        thr.start();
        thr.interrupt();
    }
}

 

==================

 

 

class MyThread extends Thread {
 private int limit = 0;
 private boolean flag = false;
 public MyThread(int limit) {
    this.limit = limit;
 }
 
 public void run() {
      int count = 0;
      while(!flag) {
      try {
  this.sleep(100);
      } catch(InterruptedException e) {}
        if(count == limit)
          flag = true;
        System.out.println(this.getName() + " : " + count);
        count++;
    }
    System.out.println(this.getName() + "종료");
 }
} 

 

===================

 

 

public class TerminateThread {

  public static void main(String args[]) {
    System.out.println("작업시작");
    MyThread r1 = new MyThread(3);
    MyThread r2 = new MyThread(7);
    MyThread r3 = new MyThread(5);
    r1.start();
    r2.start();
    r3.start();
  }
}

+ Recent posts