Created
April 26, 2014 13:43
-
-
Save 0minus273/11320381 to your computer and use it in GitHub Desktop.
Ex2q1.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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