Skip to content

Instantly share code, notes, and snippets.

@0minus273
Created April 26, 2014 13:43
Show Gist options
  • Save 0minus273/11320381 to your computer and use it in GitHub Desktop.
Save 0minus273/11320381 to your computer and use it in GitHub Desktop.
Ex2q1.java
//package mpp;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Ex2q1 {
static int counter = 0;
static Peterson counterLock = new Peterson();
public static void main(String[] args){
Integer numberOfThreads = 2;
Thread[] threads = new Thread[numberOfThreads];
long start = System.currentTimeMillis();
for (int i = 0; i < numberOfThreads; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 100000; j++) {
counterLock.lock();
try {
int localCounter = counter;
localCounter += 1;
counter = localCounter;
}
finally {
counterLock.unlock();
}
}
}
});
thread.run();
threads[i] = thread;
}
// for (Thread thread : threads) {
// thread.join();
// }
long duration = System.currentTimeMillis() - start;
System.out.println(String.format("counter=%d duration=%d", counter, duration));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment