繁体   English   中英

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

[英]How does lambda expressions work in Java?

我有这段代码,但是我不明白在有一个方法调用递增Only的部分的第37至43行。

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

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

然后在第41行中,将对t2执行run方法。 在第42行中,将对t3执行run方法。

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个构造函数调用都调用Thread(Runnable target) ,其中Runnable@FunctionalInterface ,其方法为void run() 当线程启动时,它将调用Runnablerun()方法。

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

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

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

仅供参考:该代码中没有lambda表达式 方法引用表达式不是lambda表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM