public class MyThread extends Thread{ @Override public void run() { System.out.println("線程狀態:" + Thread.currentThread().getState()); System.out.println("線程名稱:" + Thread.currentThread().getName()); System.out.println("線程優先級:" + Thread.currentThread().getPriority()); } public static void main (String args []) { MyThread t = new MyThread(); t.start(); } }
輸出:java
線程狀態:RUNNABLE 線程名稱:Thread-0 線程優先級:5
public class MyThread extends Thread { private int i = 0; public void run () { i++; System.out.println(i); } public static void main (String args []){ MyThread t = new MyThread(); t.start(); } }
1
public class MyRunnable implements Runnable { private int i =0; @Override public void run() { i++; System.out.println(i); } }
Test.java多線程
public class Test { public static void main (String args[]) { Thread t = new Thread(new MyRunnable()); t.start(); } }
輸出併發
1
public interface Future<V> { V get () throws ...; // 當任務完成時, 獲取結果 V get (long timeout, TimeUnit unit); // 在get方法的基礎上指定了超時時間 void cancel ( boolean mayInterupt); // 取消任務的執行 boolean isDone (); // 任務是否已完成 boolean isCancel (); // 任務是否已取消 }
FutureTask task = new FutureTask(new Callable);
獲得的task既是一個Runnable也是一個Future。這樣一來,能夠先把獲得的task傳入Thread構造函數中建立線程並運行(做爲Runnable使用), 接着經過task.get以阻塞的方式得到返回值(做爲Future使用)異步
import java.util.concurrent.Callable; public class MyCallable implements Callable { @Override public Object call() throws Exception { Thread.sleep(1000); return "返回值"; } }
Test.javaide
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Test { public static void main (String args []) throws ExecutionException, InterruptedException { // task同時實現了Runnable接口和Future接口 FutureTask task = new FutureTask(new MyCallable()); // 做爲 Runnable 使用 Thread t = new Thread(task); t.start(); // 做爲Future使用, 調用get方法時將阻塞直到得到返回值 System.out.println(task.get()); } }
返回值
public interface Executor { void execute(Runnable command); }
public interface ExecutorService extends Executor { void shutdown(); <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); // 其餘方法 }
public class Executors { public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } }
public class MyRunnable implements Runnable{ @Override public void run() { for (int i=0;i<3;i++) { System.out.println("MyRunnable正在運行"); } } }
import java.util.concurrent.Callable; public class MyCallable implements Callable{ @Override public Object call() throws Exception { for (int i=0;i<3;i++) { System.out.println("MyCallable正在運行"); } return "回調參數"; } }
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { public static void main (String args []) throws ExecutionException, InterruptedException { // 建立一個固定數量爲2的線程池 ExecutorService service = Executors.newFixedThreadPool(2); // 向線程池提交Callable任務,並將結果信息保存到Future中 Future callableFuture = service.submit(new MyCallable()); // 向線程池提交Runnable任務,並將結果信息保存到Future中 Future runnableFuture = service.submit(new MyRunnable()); // 輸出結果信息 System.out.printf("MyCallable, 完成:%b取消:%b返回值:%s%n", callableFuture.isDone(), callableFuture.isCancelled(), callableFuture.get()); System.out.printf("MyRunnable, 完成:%b取消:%b返回值:%s%n", runnableFuture.isDone(), runnableFuture.isCancelled(), runnableFuture.get()); // 關閉線程池 service.shutdown(); } }
MyCallable正在運行 MyCallable正在運行 MyCallable正在運行 MyCallable, 完成:true取消:false返回值:回調參數 MyRunnable正在運行 MyRunnable正在運行 MyRunnable正在運行 MyRunnable, 完成:false取消:false返回值:null
public class InteruptSimulation implements Runnable{ private volatile static boolean stop = false; @Override public void run() { try { while (!stop) { System.out.println("線程正在運行"); // 休眠5秒 Thread.sleep(5000); } System.out.println("線程終止"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main (String args []) throws InterruptedException { Thread t = new Thread(new InteruptSimulation()); t.start(); // 休眠1秒 Thread.sleep(1000); // 將共享變量stop置爲true
System.out.println("發出終止線程的信號"); stop = true; } }
線程正在運行 發出終止線程的信號 // 約5s後輸出 線程終止
public class InteruptReal implements Runnable{ @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { System.out.println("線程正在運行"); Thread.sleep(5000); } } catch (InterruptedException e) { // 發生中斷異常後,中斷狀態位會被置爲false,這裏不作任何操做 } System.out.println("線程已中斷"); } public static void main (String args []) throws InterruptedException { Thread t = new Thread(new InteruptReal()); t.start(); // 休眠1s Thread.sleep(1000); System.out.println("發出終止線程的信號"); t.interrupt(); } }
輸出:函數
線程正在運行 發出終止線程的信號 // 當即輸出 線程已中斷
線程如今已經可以及時退出啦性能
public class InteruptReal implements Runnable{ @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { System.out.println("線程正在運行"); Thread.sleep(5000); } } catch (InterruptedException e) { System.out.println("中斷狀態位:"+Thread.currentThread().isInterrupted()); } } public static void main (String args []) throws InterruptedException { Thread t = new Thread(new InteruptReal()); t.start(); // 休眠1s Thread.sleep(1000); System.out.println("發出中斷"); t.interrupt(); } }
輸出:spa
線程正在運行 發出中斷 中斷狀態位:false
public class JoinRunnable implements Runnable{ @Override public void run() { for(int i=0;i<3;i++) { System.out.println(Thread.currentThread().getName()+ "正在執行"); } } public static void main (String args[]) throws InterruptedException { Thread t = new Thread(new JoinRunnable()); t.start(); System.out.println("子線程執行完畢"); } }
子線程執行完畢 Thread-0正在執行 Thread-0正在執行 Thread-0正在執行
public class JoinRunnable implements Runnable{ @Override public void run() { for(int i=0;i<3;i++) { System.out.println(Thread.currentThread().getName()+ "正在執行"); } } public static void main (String args[]) throws InterruptedException { Thread t = new Thread(new JoinRunnable()); t.start(); t.join(); System.out.println("子線程執行完畢"); } }
輸出:操作系統
Thread-0正在執行 Thread-0正在執行 Thread-0正在執行 子線程執行完畢