Skip to content

Instantly share code, notes, and snippets.

@tacksoo
Last active December 12, 2015 00:19
Show Gist options
  • Save tacksoo/4683350 to your computer and use it in GitHub Desktop.
Save tacksoo/4683350 to your computer and use it in GitHub Desktop.
Simple thread interference example
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