Skip to content

Instantly share code, notes, and snippets.

@charlierm
Last active December 17, 2015 22:59
Show Gist options
  • Save charlierm/5686309 to your computer and use it in GitHub Desktop.
Save charlierm/5686309 to your computer and use it in GitHub Desktop.
A simple Java program showing example usage of the synchronized keyword.
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