第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Lambda 和 Runnable

Lambda 和 Runnable

牛魔王的故事 2021-08-25 15:11:44
我的理解是 Lambda 的表達式用于替換圍繞抽象實現(xiàn)的鍋爐板代碼。因此,如果我必須創(chuàng)建一個采用 Runnable 接口(Functional)的新線程,我不必創(chuàng)建一個新的匿名類,然后提供 void run() 然后在其中編寫我的邏輯,而可以簡單地使用 lambda 并指向如果方法簽名與 run 相同,即不接受任何內(nèi)容,不返回任何內(nèi)容,則將其傳遞給一個方法。但是我無法理解下面的實現(xiàn)Thread t= new Thread(()->printStudent(stud));public static void printStudent(Student stud) {        System.out.println("Student is "+ stud);    }在上述情況下,printStudent 接受一個參數(shù)(不像 runnable 的 run() 方法),盡管它以某種方式工作。這是如何工作的?
查看完整描述

2 回答

?
絕地無雙

TA貢獻1946條經(jīng)驗 獲得超4個贊

以下代碼(在類中包裝/修改您的代碼):


public class Main {


    public static void main(String[] args) {

        String item = "Hello, World!"

        Thread t = new Thread(() -> printItem(item));

        t.start();

    }


    public static void printItem(Object item) {

        System.out.println(item);

    }

}

在功能上等同于:


public class Main {


    public static void main(String[] args) {

        String item = "Hello, World!"

        Thread t = new Thread(new Runnable() {

            @Override

            public void run() {

                printItem(item);

            }

        });

        t.start();

    }


    public static void printItem(Object item) {

        System.out.println(item);

    }

}

請注意,在第一個示例中,您必須使用 lambda ( ->)。但是,您將無法使用方法引用,因為該方法printItem與Runnable. 這將是非法的:


Thread t = new Thread(Main::printItem);

基本上,方法引用與以下內(nèi)容相同:


new Runnable() {

    @Override

    public void run() {

        printItem(); // wouldn't compile because the method has parameters

    }

}

后面的表達式->,或-> {}塊內(nèi)的代碼,與您在run()方法中放置的代碼相同。


Runnable singleExpression = () -> /* this is the code inside run()*/;

Runnable codeBlock = () -> {

    // this is the code inside run()

};


查看完整回答
反對 回復 2021-08-25
?
白衣非少年

TA貢獻1155條經(jīng)驗 獲得超0個贊

您沒有將參數(shù)傳遞給run()方法,它() ->是代表run()方法的部分。你在做什么只是將方法定義為:


 @Override

 public void run(){

      printStudent(stud); //the value of stud from the context copied here

 }


查看完整回答
反對 回復 2021-08-25
  • 2 回答
  • 0 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號