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

时间:2016-11-25 02:47:11

标签: java multithreading concurrency java-threads

我有这段代码,但我不理解对incrementOnly方法调用的部分的第37到43行。

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

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

然后在第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();
    }
}

1 个答案:

答案 0 :(得分:4)

所有4个构造函数调用都在调用Thread(Runnable target),其中Runnable@FunctionalInterface,方法为void run()。线程启动后,它将调用run()的{​​{1}}方法。

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

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

总之,你将有4个线程在运行,其中两个执行ThreadDemoCounter.incrementOnly()方法,其中两个执行c1方法,所有这些都在run()的同一个实例上,即incrementOnly()

仅供参考:该代码中没有lambda expressionsmethod reference expression不是lambda表达式。