Skip to content

Instantly share code, notes, and snippets.

@kmb385
Created August 30, 2013 17:00
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 kmb385/6392037 to your computer and use it in GitHub Desktop.
Save kmb385/6392037 to your computer and use it in GitHub Desktop.
public class ThreadSafety implements Runnable {
public Integer i = 0;
@Override
public void run() {
try {
increment(this);
increment2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void increment(ThreadSafety ts) throws InterruptedException{
while(ts.i < 1000){
Thread.sleep(10);
ts.i += 1;
System.out.println(ts.i);
}
System.out.println("Final");
System.out.println(ts.i);
}
public static void increment2() throws InterruptedException{
//No race condition local variables always thread safe
//See: http://stackoverflow.com/questions/12825847/why-are-local-variables-thread-safe-in-java
int i = 0;
for(int x = 0; x < 1000; x++){
i = i + 1;
}
System.out.println(i);
}
public static void main(String[] args) {
ThreadSafety r1 = new ThreadSafety();
ThreadSafety r2 = new ThreadSafety();
new Thread(r1).start();
new Thread(r2).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment