Java創(chuàng)建線程的五種寫法總結(jié)
更新時間:2022年08月19日 10:39:16 作者:學(xué)好c語言的小王同學(xué)
本文主要為大家詳細介紹一下Java實現(xiàn)線程創(chuàng)建的五種寫法,文中的示例代碼講解詳細,對我們學(xué)習(xí)有一定的幫助,感興趣的可以跟隨小編學(xué)習(xí)一下
通過繼承Thread類并實現(xiàn)run方法創(chuàng)建一個線程
// 定義一個Thread類,相當(dāng)于一個線程的模板 class MyThread01 extends Thread { // 重寫run方法// run方法描述的是線程要執(zhí)行的具體任務(wù)@Overridepublic void run() { System.out.println("hello, thread."); } } // 繼承Thread類并重寫run方法創(chuàng)建一個線程 public class Thread_demo01 { public static void main(String[] args) { // 實例化一個線程對象 MyThread01 t = new MyThread01(); // 真正的去申請系統(tǒng)線程,參與CPU調(diào)度 t.start(); } }
通過實現(xiàn)Runnable接口,并實現(xiàn)run方法的方法創(chuàng)建一個線程
// 創(chuàng)建一個Runnable的實現(xiàn)類,并實現(xiàn)run方法 // Runnable主要描述的是線程的任務(wù) class MyRunnable01 implements Runnable { @Overridepublic void run() { System.out.println("hello, thread."); } } //通過繼承Runnable接口并實現(xiàn)run方法 public class Thread_demo02 { public static void main(String[] args) { // 實例化Runnable對象 MyRunnable01 runnable01 = new MyRunnable01(); // 實例化線程對象并綁定任務(wù) Thread t = new Thread(runnable01); // 真正的去申請系統(tǒng)線程參與CPU調(diào)度 t.start(); } }
通過Thread匿名內(nèi)部類創(chuàng)建一個線程
//使用匿名內(nèi)部類,來創(chuàng)建Thread 子類 public class demo2 { public static void main(String[] args) { Thread t=new Thread(){ //創(chuàng)建一個Thread子類 同時實例化出一個對象 @Override public void run() { while (true){ System.out.println("hello,thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); } }
通過Runnable匿名內(nèi)部類創(chuàng)建一個線程
public class demo3 { //使用匿名內(nèi)部類 實現(xiàn)Runnable接口的方法 public static void main(String[] args) { Thread t=new Thread(new Runnable() { @Override public void run() { while (true){ System.out.println("hello Thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); } }
通過Lambda表達式的方式創(chuàng)建一個線程
public class demo4 { //使用 lambda 表達式 public static void main(String[] args) { Thread t=new Thread(()->{ while (true){ System.out.println("hello,Thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); } }
到此這篇關(guān)于Java創(chuàng)建線程的五種寫法總結(jié)的文章就介紹到這了,更多相關(guān)Java創(chuàng)建線程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springbooot使用google驗證碼的功能實現(xiàn)
這篇文章主要介紹了springbooot使用google驗證碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05Spring如何基于xml實現(xiàn)聲明式事務(wù)控制
這篇文章主要介紹了Spring如何基于xml實現(xiàn)聲明式事務(wù)控制,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10Java編程思想中關(guān)于并發(fā)的總結(jié)
在本文中小編給大家整理的是關(guān)于Java編程思想中關(guān)于并發(fā)的總結(jié)以及相關(guān)實例內(nèi)容,需要的朋友們參考下。2019-09-09springboot集成CAS實現(xiàn)單點登錄的示例代碼
這篇文章主要介紹了springboot集成CAS實現(xiàn)單點登錄的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06