Skip to content

Instantly share code, notes, and snippets.

@0minus273
Created April 28, 2014 11:08
Show Gist options
  • Save 0minus273/11368612 to your computer and use it in GitHub Desktop.
Save 0minus273/11368612 to your computer and use it in GitHub Desktop.
fix.java
import java.util.concurrent;
public class Ex2q1fix {
private static class Peterson {
private final AtomicIntegerArray flag = new AtomicIntegerArray(2);
public volatile int victim;
public void lock() throws InterruptedException {
System.out.println("Aquiring lock for thread with id=" + threadLocalId.get());
int i = threadLocalId.get();
int j = 1 - i;
flag.set(i, 1);
victim = i;
while (flag[j] && victim == i) {
Thread.sleep(1);
}
System.out.println("Lock for thread with id=" + threadLocalId.get() + " aquired");
}
public void unlock() {
int i = threadLocalId.get();
flag.set(i, 0);
System.out.println("Lock for thread with id=" + threadLocalId.get() + " released");
}
}
static int counter = 0;
static ThreadLocal<Integer> threadLocalId = new ThreadLocal<Integer>();
public static void main(String[] args) throws InterruptedException {
final Peterson counterLock = new Peterson();
final int numberOfThreads = 2;
Thread[] threads = new Thread[numberOfThreads];
long start = System.currentTimeMillis();
for (int i = 0; i < numberOfThreads; i++) {
final Integer threadId = i;
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Starting thread with id=" + threadId);
threadLocalId.set(threadId);
try {
for (int j = 0; j < 100000; j++) {
counterLock.lock();
try {
int localCounter = counter;
localCounter += 1;
System.out.println("Thread[" + threadId + "] counter=" + localCounter);
counter = localCounter;
} finally {
counterLock.unlock();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
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