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