Created
August 30, 2013 17:00
-
-
Save kmb385/6392037 to your computer and use it in GitHub Desktop.
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
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