Created
February 1, 2015 23:20
-
-
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
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
| 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