Last active
December 12, 2015 00:19
-
-
Save tacksoo/4683350 to your computer and use it in GitHub Desktop.
Simple thread interference example
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 Nondeterministic { | |
private int x = 0; | |
private int y = 1; | |
/* | |
* What happens when you synchronize only the write()? | |
* A synchrnoized method is like a bathroom with a door but without walls | |
*/ | |
/* | |
* public void write() { x = 2; y = 3; System.out.println("x: " + x + | |
* ", y: " + y); } | |
*/ | |
public synchronized void write() { | |
x = 2; | |
y = 3; | |
System.out.println("write: x: " + x + ", y: " + y); | |
} | |
public void read() { | |
System.out.println("read: x: " + x + ", y: " + y); | |
x = 0; | |
y = 1; | |
} | |
public static void main(String[] args) { | |
final Nondeterministic nd = new Nondeterministic(); | |
Thread t1 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
while (true) | |
{ | |
nd.read(); | |
try { | |
Thread.sleep(500); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
Thread t2 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
while (true) { | |
nd.write(); | |
try { | |
Thread.sleep(500); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment