2016-11-25 34 views
2

我有這個代碼,但我不明白第37至43行上有方法調用incrementOnly的部分。lambda表達式在Java中如何工作?

繼承人我的理解(這是正確的嗎?) T2將只在線路創建一個新的線程35

T3將在第36行創建一個新的線程,那麼它會調用該方法incrementOnly。

然後在第41行,run方法將執行t2。在第42行,run方法將在t3中執行。

package aa.race; 

import java.util.concurrent.ForkJoinPool; 
import java.util.concurrent.locks.Lock; 
import java.util.concurrent.locks.ReentrantLock; 

public class ThreadDemoCounter implements Runnable 
{ 
    int counter; 
    int alternate; 
    String name; 


    public static int numLoops = 4; 
    public static int numPrints = 1500; 

    public ThreadDemoCounter(String n) 

    { 
     name = n; 
     counter = 0; 
    } 


    // For bonus -- delete method go. Change main to below code: 
    public static void main(String[] args) throws Exception 
    { 
     ThreadDemoCounter c1 = new ThreadDemoCounter("c1"); 
     //Run the multithreaded demo a few times 
     for (int foo = 0; foo < numLoops; foo++) 
     { 
      c1.counter = 0; 

      Thread t1 = new Thread(c1); 
      Thread t2 = new Thread(c1); 

      Thread t3 = new Thread(c1::incrementOnly); 
      Thread t4 = new Thread(c1::incrementOnly); 

      t1.start(); 
      t2.start(); 
      t3.start(); 
      t4.start(); 


      t1.join(); 
      t2.join(); //wait for both 
      t3.join(); 
      t4.join(); //wait for both 

      System.out.println("c1 = " + c1.counter); 
      System.out.println("===== end loop ====="); 
     } 

    } 


    public void incrementOnly() 
    { 
     for (int i =0 ; i < numPrints; i++) 
     { 
      incrementCounter(); 
     } 
    } 

    public void run() 
    { 

     for (int j = 0; j < numPrints; j++) 
     { 


      LockFactory.getLock(name).lock(); 
      System.out.println("counter " + name + " = " + getCounter() + " retrieved by thread: " + Thread.currentThread().getName()); 

      incrementCounter(); 
      LockFactory.getLock(name).unlock(); 

     } 
     System.out.println(); 
    } 

    public int getCounter() 
    { 
     return counter; 
    } //start at 0 

    public void incrementCounter() 
    { 
     LockFactory.getLock(name).lock(); 

     counter++; 
     LockFactory.getLock(name).unlock(); 
    } 
} 

回答

4

所有4構造函數調用呼籲Thread(Runnable target),其中Runnable@FunctionalInterface與方法void run()。當線程啓動時,它將調用方法Runnable

前兩個構造函數調用new Thread(c1)在流逝的ThreadDemoCounter一個實例,因此這兩個線程將呼籲c1實例ThreadDemoCounter.run()方法。

另外兩個構造函數調用將method reference傳遞給c1incrementOnly()方法。這是一種有效的方法,因爲它也是一種無參的無效方法。這兩個線程將調用c1實例的ThreadDemoCounter.incrementOnly()方法。

總之,你就會有4個線程運行,他們兩個執行run()方法,其中兩個執行incrementOnly()方法,對所有的ThreadDemoCounter相同的實例,即c1

供參考:該代碼中沒有lambda expressions。 A method reference expression不是lambda表達式。

+0

優秀的解釋。謝謝! – NoMoreErrors