gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:50:55 28 4
gpt4 key购买 nike

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

这是我的理解(这是正确的吗?)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();
}
}

最佳答案

所有 4 个构造函数调用都在调用 Thread(Runnable target) , 其中Runnable@FunctionalInterface使用方法 void run()。当线程启动时,它会调用Runnablerun()方法。

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

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

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

仅供引用:没有 lambda expressions在该代码中。 method reference expression不是 lambda 表达式。

关于java - lambda 表达式在 Java 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com