lambda 表达式在 Java 中如何工作?

How does lambda expressions work in Java?

我有这段代码,但我不明白第 37 到 43 行中调用 incrementOnly 的部分。

这是我的理解(正确吗?) t2 只会在第 35 行创建一个新线程

t3 将在第 36 行创建一个新线程,然后它会调用方法 incrementOnly。

然后在第 41 行,运行 方法将为 t2 执行。在第 42 行,运行 方法将为 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 个构造函数调用都使用方法 void run() 调用 Thread(Runnable target), where Runnable is a @FunctionalInterface。当线程启动时,会调用Runnable.

run()方法

前两个构造函数调用 new Thread(c1) 正在传递 ThreadDemoCounter 的实例,因此这两个线程将为 c1 实例调用 ThreadDemoCounter.run() 方法。

另外两个构造函数调用正在将 method reference 传递给 c1incrementOnly() 方法。这是一个有效的方法,因为它也是一个无参数的 void 方法。这两个线程将为 c1 实例调用 ThreadDemoCounter.incrementOnly() 方法。

总共有 4 个线程 运行,其中两个执行 run() 方法,另外两个执行 incrementOnly() 方法,都在同一个实例上ThreadDemoCounter,即 c1

仅供参考: 没有 lambda expressions in that code. A method reference expression 不是 lambda 表达式。