lambda替换匿名的新Runnable()的方式如何工作?

时间:2018-10-28 02:13:33

标签: java lambda runnable anonymous-class

编写匿名 Runnable 时,例如:

 for (int customer=0; customer<numberOfCustomers; customer++) {
                try {
                    // get amount used by customer as String, convert to double
                    GBused = Double.valueOf(Accounts[customer][USED]);

                    // compute bill based on the customer's plan selection
                    switch (Accounts[customer][SELECTION]) {
                        case "Plan-A":
                            bill = computeBill (GBused, PLAN[A][LIMIT], PLAN[A][PRICE]);
                            break;
                        case "Plan-B":
                            bill = computeBill (GBused, PLAN[B][LIMIT], PLAN[B][PRICE]);
                            break;
                        case "Plan-C":
                            bill = computeBill (GBused, PLAN[C][LIMIT], PLAN[C][PRICE]);
                            break;
                        case "Plan-D":
                            bill = computeBill (GBused, PLAN[D][LIMIT], PLAN[D][PRICE]);
                            break;
                        default:
                            bill = 0.00;
                            break;
                    }
                    // convert the bill to a String and save into the array
                    Accounts[customer][BILL] = String.valueOf(bill);                
                } // end of try               
                catch (NumberFormatException e) {
                    System.out.println ("Values for GB used must be numeric");               
                } 

IntelliJ建议将其替换为以下lambda:

Thread producer = new Thread(new Runnable() {
      @Override
      public void run() {
        // do something
      }
});

效果很好

这是如何工作的?特别是:

  1. 所使用的构造函数仍为Thread producer = new Thread(() -> { // do something } }); ,但lambda中似乎没有任何内容表明它是可运行的。
  2. 为什么突然不再需要Thread(Runnable target)

1 个答案:

答案 0 :(得分:2)

如果您的匿名类只有一个方法,则可以将其实现为lambda表达式。您在此处作为lambda传递的是run方法的实现。 Lambda表达式使您可以更紧凑地表达单方法类的实例。