I have this code but I do not understand lines 37 to 43 on the part where there is a method call to incrementOnly.
Heres my understanding (Is this correct?) t2 will just create a new thread at line 35
t3 will create a new thread at line 36, then it will call the method incrementOnly.
Then in line 41, run method will be executed for t2. In line 42, run method will be executed for 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();
}
}
All 4 constructor calls are calling Thread(Runnable target)
, where Runnable
is a @FunctionalInterface
with the method void run()
. When the thread is started, it will call the run()
method of the Runnable
.
The first two constructor calls new Thread(c1)
is passing an instance of ThreadDemoCounter
, so those two threads will call the ThreadDemoCounter.run()
method for the c1
instance.
The other two constructor calls are passing a method reference to the incrementOnly()
method of c1
. That is a valid method because it is also a no-arg void method. Those two threads will call the ThreadDemoCounter.incrementOnly()
method for the c1
instance.
In all, you'll have 4 threads running, two of them executing the run()
method, and two of them executing the incrementOnly()
method, all on the same instance of ThreadDemoCounter
, i.e. c1
.
FYI: There are no lambda expressions in that code. A method reference expression is not a lambda expression.