1: package Test_Thread;
2:
3: public class Test_Thread {
4:
5: /**
6: * @param args
7: */
8: public static void main(String[] args) throws Exception{
9:
10: System.out.println(Thread.currentThread().getName()+" Start");//取得目前執行緒名稱
11:
12: /**繼承 Thread 類別達到多執行緒*/
13: ThreadA ta = new ThreadA();
14: ta.sleep(3000);//等待3秒
15: ta.start();//使用 start 方法啟動執行緒
16: ta.join();//等待 ta 執行緒先完成再讓其他執行緒運作
17:
18:
19: /**實作 Runnable 介面達到多執行緒*/
20: ThreadB tb = new ThreadB();
21: Thread tbThread = new Thread(tb);
22: tbThread.setName("tbThread");
23:
24: /**實作 Runnable 介面達到多執行緒*/
25: Thread tbThread2 = new Thread(tb);
26: tbThread2.setName("tbThread2");
27:
28: /**實作 Runnable 介面達到多執行緒*/
29: Thread tbThread3 = new Thread(tb);
30: tbThread3.setName("tbThread3");
31: tbThread.start();//使用 start 方法啟動執行緒
32: tbThread3.start();//使用 start 方法啟動執行緒
33: tbThread2.start();//使用 start 方法啟動執行緒
34:
35: }
36:
37: }
38:
39: /**繼承 Thread 類別達到多執行緒*/
40: class ThreadA extends Thread//繼承 Thread 類別
41: {
42:
43: public void run()//改寫 run 方法
44: {
45: super.setName("taThread");//設定 Thread 的名稱
46:
47: for(int i =0; i<20; i++)
48: {
49:
50: System.out.println(Thread.currentThread().getName()+" Run");
51: }
52:
53: }
54: }
55:
56: /**實作 Runnable 介面達到多執行緒*/
57: class ThreadB implements Runnable //實作 Runnable 介面
58: {
59: private int testCount = 0;
60:
61: public void run()
62: {
63: //使用 synchronized 鎖定區塊中的方法或物件只能給單一執行緒使用
64: synchronized (this) {
65:
66: for(int i = 0; i<10; i++)
67: {
68:
69: testCount++;
70: System.out.println(Thread.currentThread().getName()+" Run"+i+" testCount:"+testCount);
71: }
72: }
73: }
74: }