Skip to content

Instantly share code, notes, and snippets.

@smamran
Created September 15, 2015 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smamran/e57365434f488bcbf1f4 to your computer and use it in GitHub Desktop.
Save smamran/e57365434f488bcbf1f4 to your computer and use it in GitHub Desktop.
Java Thread with Synchronized Thread Join
class Worker {
private static long count = 0;
public synchronized void increment() {
for (int i = 0; i < 10; i++) {
count++;
}
}
public void run() {
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (long i = 0; i < 10; i++) {
increment();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (long i = 0; i < 10; i++) {
increment();
}
}
});
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count is: " + count);
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
new Worker().run();
System.out.println("Done in: " + (System.currentTimeMillis() - start));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment