2011년 5월 23일 월요일

Java -Thread

자세한 개념은 생략

1. 구현 방법 두가지가 있음
  (1) Thread 클래스 상속
     public MyThread extends Thread{
          public voic run(){
               System.out.println("Hello World");
          }

          public static void main(String[] args){
               (new MyThread()).start();
          }
     }

  (2) Runnable 인터페이스 구현
     public MyRunnable implements Runnable{

          public voic run(){
               System.out.println("Hello World");
          }

          public static void main(String[] args){
               (new Thread(new MyRunnable())).start();
          }

     }

   공통점 - run() 에 구현하고  start()로 실행한다.
   차이점 - (1)은 상속 (2)는 구현, 다른 클래스를 상속하는 Thread를 사용하고 싶으면 (2)번 방법을 쓸 수 밖에 없다.


2. 주요 method
  (1) sleep(int millisec)
    millisec( 1/1000초 1초 = 1000 밀리세컨즈) 만큼 thread를 재우고 다른 thread를 수행한다.
    e.g. for (int i = 0; i < importantInfo.length; i++) {
         try {
             Thread.sleep(4000);
         } catch (InterruptedException e) {
             //We've been interrupted: no more messages.
             return;
         }
         //Print a message
         System.out.println(importantInfo[i]);
     }
    출처 - http://download.oracle.com/javase/tutorial/essential/concurrency/sleep.html


  (2) join()
     해당 thread가 완료될때까지 기다리게 한다. 시간을 설정 할 수도 있다.
     e.g. myThread.join(); // myThread가 완료될때까지 다른  thread는 멈춘다.

댓글 없음:

댓글 쓰기