Created
September 15, 2015 05:24
-
-
Save smamran/e57365434f488bcbf1f4 to your computer and use it in GitHub Desktop.
Java Thread with Synchronized Thread Join
This file contains 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
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