본문 바로가기

프로그래밍/JAVA

자바 쓰레드 예제(JAVA Thread example)




간단한 자바 쓰레드 예제입니다. 보통 쓰레드는 run()메소드를 구현합니다.
run()메소드 내의 내용이 프로세스 실행고는 독립적으로 실행됩니다.
Thread 클래스를 extends해서 사용하는법과 Runnable 인터페이스를 implements해서 사용하는법이 있습니다.
참고로 쓰레드를 사용하면 동기화가 되지 않으므로 쓰레드에 안전하게 동기화를 위해서는 synchronized 키워드를 사용하여 동기화를 시켜줍니다.

1. Theard 클래스를 extends하는법

class SimpleTheard extends Thread {
 int from,to;
 public SimpleTheard(int from,int to) {
this.from=from; this.to=to; } public void run() { for(int i=from;i<=to;i++) { System.out.println(" i = "+i); } } public static void main(String[] args) { for(int i=0;i<10;i++) { SimpleTheard t =new SimpleTheard (i*500,(i+1)*500); t.start(); } } }

2. Runnable 인터페이스를 implements하는법

public class robin implements Runnable
{
  private String indiword;
  private long tic;

  public robin(String indiword, long tic)
  {
    this.indiword = indiword;
    this.tic = tic;
  }

  public static void main (String[] args)
  {
    Thread one = new Thread(new robin("Plip ",300L));
    Thread two = new Thread((Runnable) new robin("Plop\n",800L));
    one.setDaemon(true);
    two.setDaemon(true);

    System.out.println("Here they come ...");
    one.start();
    two.start();

    try
    {
       System.in.read();
    }
    catch (Exception e)
    {
       System.out.println("Exception "+e);
    }
    one.stop();
    two.stop();
  }

  public void run()
  {
    while (true)
    {
      System.out.print(indiword);
      try {
        Thread.sleep(tic);
        }
      catch (Exception e)
      {
         System.out.println("Exception "+e);
      }
    }
  }
}