Skip to content

Instantly share code, notes, and snippets.

@revox
Created February 1, 2015 23:20
Show Gist options
  • Select an option

  • Save revox/ff9a0bf9996884022dce to your computer and use it in GitHub Desktop.

Select an option

Save revox/ff9a0bf9996884022dce to your computer and use it in GitHub Desktop.
Example of thread deadlock, uncomment the counter to see interleaving then uncomment the synchronised statements to see deadlock
class Friend {
String name;
public Friend(String name) {
this.name = name;
}
public /* synchronized */ void waveAt(Friend f) {
System.out.println(name + " waves...");
int a=0;
//for (int i =0;i<10000000;i++) {
// a++;
// }
f.waveBack();
}
public /* synchronized */ void waveBack() {
System.out.println(name + " waves back.");
}
}
class greet extends Thread
{
Friend one,two;
greet(Friend f, Friend g)
{
one=f;
two=g;
}
public void run() {
one.waveAt(two);
}
}
public class Deadlock {
public static void main(String[] args) {
Friend fred = new Friend("Alice");
Friend jack = new Friend("Bob");
new greet(fred,jack).start();
new greet(jack,fred).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment