Last active
December 17, 2015 22:59
-
-
Save charlierm/5686309 to your computer and use it in GitHub Desktop.
A simple Java program showing example usage of the synchronized keyword.
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
import java.lang.Runnable; | |
import java.lang.Thread; | |
/** | |
* The Main Class. | |
**/ | |
public class Collision { | |
/** | |
* Main entry point into the application. | |
**/ | |
public static void main(String[] args) { | |
Incrementer incrementer = new Incrementer(); | |
Thread[] threads = new Thread[100]; | |
for (int i=0; i<100; i++) { | |
threads[i] = new Thread(incrementer); | |
threads[i].start(); | |
} | |
for (Thread thread : threads) { | |
try{ | |
thread.join(); | |
} | |
catch (java.lang.InterruptedException e){ | |
System.out.println("Failed to join"); | |
} | |
} | |
System.out.println(String.format("Total: %s", incrementer.count)); | |
} | |
} | |
/** | |
* Incrementer class used to increment the Incrementer Class. | |
**/ | |
class Incrementer implements Runnable{ | |
public int count; | |
public void increment(){ | |
this.count ++; | |
} | |
/** | |
* Implemented method, runs in a thread. | |
**/ | |
@Override | |
public synchronized void run(){ | |
this.increment(); | |
System.out.println(String.format("Count: %s", this.count)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment