Skip to content

Instantly share code, notes, and snippets.

@0minus273
Last active August 29, 2015 13:59
Show Gist options
  • Save 0minus273/10717203 to your computer and use it in GitHub Desktop.
Save 0minus273/10717203 to your computer and use it in GitHub Desktop.
wtfiswrong.java
//package mcp;
public class outpit {
static int counter = 0;
public static void main(String[] args) throws InterruptedException {
if (args.length < 1) {
throw new IllegalArgumentException("Usage: Ex1q9 N");
}
Integer numberOfThreads = Integer.valueOf(args[0]);
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 < 5; j++) {
int localCounter = counter;
localCounter += 1;
counter = localCounter;
System.out.println(String.format("counter=%d thread=%d", counter, i));
}
}
});
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