JAVA

스레드

꿀꿀이냐옹이 2011. 8. 10. 15:48
반응형

1. Frame의 상속과 Runnable의 구현

import java.awt.Frame;

/**
 * Frame의 상속과 Runnable의 구현 Thread를 상속하지 못하는 경우 Runnable로 구현
 */

class RunFrame extends Frame implements Runnable {
 public void run() {
  int i = 0;
  System.out.println("스레드 시작!");
  while (i < 20) {
   System.out.print(i + "\t");
   this.setTitle("스레드 동작중" + i++);
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
    System.out.println(e);
   }
  }
  System.out.println("스레드 종료!");
 }
}

public class RunFrameMain {
 public static void main(String[] args) {
  RunFrame r = new RunFrame();
  r.setSize(300, 100);
  r.setVisible(true);
  Thread t = new Thread(r);
  t.start();
 }
}

2. Frame 내부에서 스레드 동작 시키기

import java.awt.Frame;

/**
 *  Frame 내부에서 스레드 동작 시키기
 */
class RunnableFrame extends Frame implements Runnable {
 public RunnableFrame() {
  new Thread(this).start();
 }

 public void run() {
  int i = 0;
  System.out.println("스레드 시작!");
  while (i < 20) {
   System.out.println(i + "\t");
   this.setTitle("스레드 동작중" + i++);
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
    System.out.println(e);
   }
  }
  System.out.println("스레드 종료!");
 }
}

public class RunnableFrameMain {
 public static void main(String[] args) {
  RunnableFrame r = new RunnableFrame();
  r.setSize(300, 100);
  r.setVisible(true);
 }
}


3. Frame과 Thread 분리시켜서 구현

import java.awt.Frame;

/** * Frame과 Thread 분리시켜서 구현 */
class SoloFrame extends Frame {
 public SoloFrame() {
  SoloThread t = new SoloThread(this);
  t.start();
 }
}

class SoloThread extends Thread {
 private Frame f = null;

 public SoloThread(Frame f) {
  this.f = f; // SoloFrame의 참조값 챙겨두기
 }

 public void run() {
  int i = 0;
  System.out.println("스레드 시작!");
  while (i < 20) {
   System.out.print(i + "\t");
   f.setTitle("스레드 동작중" + i++);
   try {
    this.sleep(300);
   } catch (InterruptedException e) {
    System.out.println(2);
   }
  }
  System.out.println("스레드 종료!");
 }
}

public class SoloFrameMain {
 public static void main(String args[]) {
  SoloFrame s = new SoloFrame();
  s.setSize(300, 100);
  s.setVisible(true);
 }
}

반응형