JAVA 三种线程实现创建方式
生活随笔
收集整理的這篇文章主要介紹了
JAVA 三种线程实现创建方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JAVA 三種線程實現/創建方式
方式一:繼承Thread類
通過繼承Thread類來創建一個自定義線程類。Thread類本質上就繼承了Runable接口,代表一個線程類。啟動線程的唯一辦法就是通過Thread類的start()實例方法。start()方法是一個 native 方法(本地方法),它將啟動一個新線程,并執行 run()方法。
public class MyThread extends Thread { //重寫父類的run方法,實現自定義線程操作public void run() { System.out.println("MyThread.run()"); } public static void main(String[] args){MyThread myThread1 = new MyThread(); //通過start()啟動線程myThread1.start();} }Java只支持單繼承,這也導致了如果使用繼承Thread類創建的線程,就無法繼承其他類,這也是不推薦使用Thread類創建線程的原因之一。
方式二:實現Runnable接口
如果自己的類已經 extends 另一個類,就無法直接 extends Thread,此時,可以實現一個Runnable 接口來避免這種情況。
public class MyThread implements Runnable { public void run() { System.out.println("MyThread.run()"); } public static void main(String[] args){MyThread myThread1 = new MyThread(); //傳入實現runnable接口的實例Thread thread = new Thread(myThread); //通過start()啟動線程thread.start();} }我們也可以寫成這樣
public class MyThread{ public static void main(String[] args){//直接通過匿名類創建線程Thread thread = new Thread(new Runnable(){public void run() { System.out.println("MyThread.run()"); } }); //通過start()啟動線程thread.start();//或者使用lambda表達式,這樣更加便捷Thread thread2 = new Thread(()->{System.out.println("MyThread.run()"); })thread2.start();} }方式三:通過ExecutorService、Callable、Future創建有返回值線程
有返回值的任務必須實現 Callable 接口,類似的,無返回值的任務必須 Runnable 接口。執行Callable 的任務后會放回一個Future 的對象,而這個Future對象上調用 get 就可以獲取到 Callable 任務返回的 Object 了。線程池接口 ExecutorService定義了執行Callable接口的方法。
ExecutorService接口定義了submit()方法用于接受提交到線程池的任務,并放回一個Future對象。
Future對象用于獲取線程任務放回值,我們通過Future對象的get方法獲取放回值。
//創建一個大小為5的線程池 ExecutorService pool = Executors.newFixedThreadPool(5);// 向線程池提交一個執行任務并獲取 Future 對象 Future f = pool.submit(new Callable(){public int call() {System.out.println("MyThread.run()");return 10;} }); // 關閉線程池 pool.shutdown(); // 獲取所有并發任務的運行結果 for (Future f : list) // 從 Future 對象上獲取任務的返回值,并輸出到控制臺System.out.println("res:" + f.get().toString());總結
以上是生活随笔為你收集整理的JAVA 三种线程实现创建方式的全部內容,希望文章能夠幫你解決所遇到的問題。