Skip to content

Instantly share code, notes, and snippets.

@VincentTatan
Created October 21, 2015 06:14
Show Gist options
  • Save VincentTatan/b8b7421f33fdac5c04a1 to your computer and use it in GitHub Desktop.
Save VincentTatan/b8b7421f33fdac5c04a1 to your computer and use it in GitHub Desktop.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadDemoCounter implements Runnable
{
private static Lock lock = new ReentrantLock();
private int counter;
public int getCounter()
{
return counter;
}
public void incrementCounter()
{
counter++;
}
public static final int numLoops = 4;
public static final int numPrints = 10;
public ThreadDemoCounter()
{
counter = 0;
}
public void go() throws Exception
{
//Run the multithreaded demo a few times
for (int foo = 0; foo < numLoops; foo++)
{
counter = 0; //reset
Thread t1 = new Thread(this);
Thread t2 = new Thread(this);
t1.start();
t2.start();
t1.join();
t2.join(); //wait for both
System.out.println("===== end loop =====");
}
}
public static void main(String[] args) throws Exception
{
ThreadDemoCounter t = new ThreadDemoCounter();
t.go();
}
public void run()
{
lock.lock();
for (int j = 0; j < numPrints; j++)
{
System.out.println("counter = " + getCounter());
incrementCounter();
}
System.out.println();
lock.unlock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment