線程的創建
阿新 • • 發佈:2018-03-24
接口 當前 @override except exti 調用 thread nbsp star
基本線程類:
Thread
MyThread my = new MyThread(); my.start();
1 //當前線程可轉讓cpu控制權,讓別的就緒狀態線程運行(切換) 2 public static Thread.yield() 3 //暫停一段時間 4 public static Thread.sleep() 5 //在一個線程中調用other.join(),將等待other執行完後才繼續本線程。 6 public join() 7 //中斷線程-> 8 //終端只會影響到wait狀態、sleep狀態和join狀態。被打斷的線程會拋出InterruptedException。9 //正常線程不會去檢測 不受影響 10 public interrupte()
Runnable
1 public class MyRunnable implements Runnable{ 2 @Override 3 public void run() { 4 System.out.println("my runnable running !"); 5 } 6 public static void main(String[] args) { 7 Runnable myRunable = new MyRunnable();8 Thread myThread = new Thread(myRunable); 9 myThread.start(); 10 } 11 }
Callable , Future
FutureTask 實現了 future接口和runnable接口
1 public class MyCallable implements Callable<Integer>{ 2 @Override 3 public Integer call() throws Exception { 4 Integer i = newRandom().nextInt(); 5 return i; 6 } 7 public static void main(String[] args) { 8 //創建 callable 9 MyCallable myCallable = new MyCallable(); 10 //可以接收 callable 的返回值 判斷線程終止 11 FutureTask<Integer> future = new FutureTask(myCallable); 12 //開啟線程 13 new Thread(future).start(); 14 } 15 }
線程的創建