java多執行緒——簡化執行緒使用以及lambda快速入門
簡化執行緒的使用
1、靜態內部類
class MyThread{ static class test implements Runnable{ public void run(){ for(int i=0;i<10;i++){ System.out.println("學習_(:з」∠)_"); } } } public static void main(String[] args){ new Thread(new test()).start();
執行結果
對於只使用一次的,可以使用內部類加快執行速率,它的特點是,只有使用時才會進行編譯,且內部類的引用更快。
2、方法中的類(區域性內部類)
class MyThread{ public static void main(String[] args){ class test implements Runnable{ public void run(){ for(int i=0;i<10;i++){ System.out.println("學習
將內部類移動到方法裡面
3、匿名內部類
需要藉助介面或者是父類
class MyThread{ public static void main(String[] args){ new Thread(new Runnable() { @Override public void run() { for
執行結果
只針對較為簡單的方法
4、匿名內部類,且簡化run方法
例項:
class MyThread{ public static void main(String[] args){ new Thread(()->{ for(int i=0;i<10;i++){ System.out.println("噠噠的馬蹄"); } }).start(); } }
執行結果
lamdba表示式,對於一個方法可以推匯出介面和類
lambda表示式快速入門
基本語法
(parameters)-> expression
(paramenters) -> { statements; }
例項:
簡單表示式
()->“hello word”
無引數,返回一個字串
(x)->”the content is:”+x;
接受一個引數,返回一個字串
(x,y)->x+y
接受兩個引數,返回一個值
(String x)->”this is the string:”+x;
接受一個字串引數,返回一個字串