我有这段代码,但我不明白第 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()
。当线程启动时,会调用run()
Runnable
的方法.
前两个构造函数调用 new Thread(c1)
正在传递 ThreadDemoCounter
的实例,所以这两个线程将调用 ThreadDemoCounter.run()
c1
的方法实例。
另外两个构造函数调用传递 method reference到incrementOnly()
方法c1
。这是一个有效的方法,因为它也是一个无参数的 void 方法。这两个线程将调用 ThreadDemoCounter.incrementOnly()
c1
的方法实例。
总共,您将运行 4 个线程,其中两个执行 run()
方法,其中两个执行 incrementOnly()
方法,全部在 ThreadDemoCounter
的同一个实例上,即c1
.
仅供引用:没有 lambda expressions在该代码中。一个method reference expression不是 lambda 表达式。
关于java - Java 中的 lambda 表达式如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796984/