Created
May 18, 2015 16:42
-
-
Save markormesher/269bf6955132e59f297c to your computer and use it in GitHub Desktop.
Demonstrates deadlock between two objects calling synchronised methods of each other
This file contains hidden or 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 SyncTest { | |
public static Obj1 obj1; | |
public static Obj2 obj2; | |
public static void main(String... args) { | |
obj1 = new Obj1(); | |
obj2 = new Obj2(); | |
Thread t1 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
while (true) { | |
obj1.a(obj2); | |
System.out.println("No lock yet"); | |
try { | |
Thread.sleep(10); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
Thread t2 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
while (true) { | |
obj2.a(obj1); | |
System.out.println("No lock yet"); | |
try { | |
Thread.sleep(10); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} | |
public static class Obj1 { | |
public synchronized void a(Obj2 other) { | |
other.b(this); | |
} | |
public synchronized void b(Obj2 other) { | |
System.out.println("Called by " + other.toString()); | |
} | |
} | |
public static class Obj2 { | |
public synchronized void a(Obj1 other) { | |
other.b(this); | |
} | |
public synchronized void b(Obj1 other) { | |
System.out.println("Called by " + other.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment