一 繼承thread類
1. 定義Thread的子類,重寫run()方法,run()方法稱為線程執行體
2. 創建Thread子類的實例
3. 調用線程對象的start()方法啟動線程
public class MyThread extends Thread { @Override public void run() { for (int i=0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + " is running " + i); } } public static void main(String[] args) { new MyThread().start(); new MyThread().start(); } }
運行結果如下圖所示:
二:實現runnable接口
1.定義runnable接口的實現類,重寫run()方法
2.創建Runnable實現類的實例,丟入到Thread對象
3.調用線程對象的start()方法來啟動線程
public class RunnableTest implements Runnable { @Override public void run() { for(int i=0;i<3;i++){ try { Thread.sleep(100); System.out.println(Thread.currentThread().getName()+i); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { new Thread(new RunnableTest(),"線程1---").start(); new Thread(new RunnableTest(),"線程2---").start(); } }
運行結果如下圖所示
三:實現Callable接口
在Java5之后就開始提供Callable接口,該接口是Runnable接口的增強版,Callable接口提供了一個call()方法作為線程執行體,call()方法可
以有返回值,call()方法可以聲明拋出異常。
V get() 返回Call任務里call方法的返回值。調用該方法會造成線程阻塞,必須等待子線程結束后才會得到返回值。
V get(long timeout,TimeUnit unit)返回Call任務里call方法的返回值,該方法限定程序最多阻塞timeout和unit指定的時間,
如果超過指定時間還沒有返回值,將會拋出TimeOutException異常
boolean isCancelled()如果在Callable任務正常完成前被取消,則返回true
boolean isDone() 如果Callable任務完成則返回true。
Callable的實現步驟如下:
1.創建Callable接口的實現類,並實現call方法
2.使用FutureTask類包裝Callable對象
3.使用FutrueTask對象作為Thread對象的target創建並啟動新線程
4.啟用FutrueTask對象的get()方法獲得子線程的返回值。
public class CallableDemo implements Callable<Integer> { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Integer> futureTask=new FutureTask<Integer>(new CallableDemo()); new Thread(futureTask).start(); try { System.out.println("線程返回值是"+futureTask.get()); }catch (Exception e){ e.printStackTrace(); } if(futureTask.isDone()){ System.out.println("線程結束"); } } @Override public Integer call() throws Exception { System.out.println("線程開始"); int sum=0; for(int i=0;i<100;i++){ sum+=i; } return sum; } }
運行結果如下圖所示: