我有這個代碼,但我不明白第37至43行上有方法調用incrementOnly的部分。lambda表達式在Java中如何工作?
繼承人我的理解(這是正確的嗎?) T2將只在線路創建一個新的線程35
T3將在第36行創建一個新的線程,那麼它會調用該方法incrementOnly。
然後在第41行,run方法將執行t2。在第42行,run方法將在t3中執行。
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();
}
}
優秀的解釋。謝謝! – NoMoreErrors