利用Lambda表達式創(chuàng)建新線程案例
更新時間:2020年08月26日 11:14:52 作者:cakincheng
這篇文章主要介紹了利用Lambda表達式創(chuàng)建新線程案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
代碼
public class LamdaDemo { public static void main( String[] args ) { Runnable task = () -> { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }; task.run(); Thread thread = new Thread(task); thread.start(); System.out.println("Done!"); } }
運行
Hello main Done! Hello Thread-0
補充知識:java_Thread多線程創(chuàng)建和lambda
我就廢話不多說了,大家還是直接看代碼吧~
/** * * @author Mr_zhou * 2018年9月3日 下午6:42:38 <br/> * TODO java多線程 */ //----------------方式一實現(xiàn)Runnable接口---------------- public class TestThread implements Runnable { public static void main(String[] args) { ThreadPring(); } static void ThreadPring() { //-------------------------方式二,new一個Runnable()匿名內(nèi)部類---------------- Runnable run2=new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }; //------------------------方式三,lambda簡寫,jdk1.8特性---------------- Runnable run=()-> { System.out.println(Thread.currentThread().getName()); }; new Thread(run).start(); new Thread(run2).start(); new Thread(new TestThread()).start(); new myThread().start(); } @Override public void run() { try { //線程休眠3秒 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } } //--------------方式四,繼承線程類Thread---------------- class myThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }
以上這篇利用Lambda表達式創(chuàng)建新線程案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Netty搭建WebSocket服務(wù)器實戰(zhàn)教程
這篇文章主要介紹了Netty搭建WebSocket服務(wù)器實戰(zhàn),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03