簡體   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