Java Thread簡介

底下先用一個簡單的例子說明,二個Thread各自執行的結果:

你可以implements java.lang.Runnable 或是 extends java.lang.Thread

public class TestThread extends java.lang.Thread { 

  public long waittime; 
  public String data; 

  public TestThread(long waittime, String value) { 
    this.waittime = waittime; 
    this.data = value; 
  } 

  public void run()// 啟動Thread時會執行run 
  { 
    try { 
      while (true) {// 永遠讓Thread執行下去,只有在強制中斷時才會失效 
        // 停幾秒後執行System內容 
        Thread.sleep(waittime); 
        System.out.println(this.data); 
      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 

  } 

  public static void main(String args[]) { 
    // 1000毫秒 = 1秒 
    // 用start 來啟動thread 
    (new TestThread(3 * 1000, "Thread-1")).start(); 
    (new TestThread(1 * 1000, "Thread-2")).start(); 

  } 
}

結果如下:(可能會有所不同)

Thread-2
Thread-2
Thread-1
Thread-2
Thread-2
Thread-2
Thread-1
Thread-2
Thread-2
Thread-2

發表迴響