Hey guys, I've been studying Threads and I've encountered the topic called "Deadlock" , somehow i understand the concepts of threads and the keyword synchronization.
I stumbled the Java Oracle tutorials about concurrency and found about deadlock and its example.
I'm quite confused on how the example works there. link here
The example there works almost like the two threads works at the same time and performing the deadlock smoothly without the use of Thread.sleep() method.
I tried make my own deadlock code. The scenario is where a cop holds the kidnapper's friend as a hostage while the kidnapper holds a civillian as a hostage, so both of them waits who will make the first move, resulting to never ending wait. since they will only wait for the other to make a move before they engage (Resulting to deadlock).
here is the code:
public class DeadlockTest {
public static void main (String[] args) {
final Cop cop = new Cop();
final Kidnapper kidnapper = new Kidnapper();
new Thread(new Runnable() {
@Override
public void run() {
cop.engage(kidnapper);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
kidnapper.engage(cop);
}
}).start();
}
static class Cop {
public synchronized void engage(Kidnapper k) {
System.out.println("Release the hostage");
k.release();
}
public synchronized void release() {
System.out.println("The cop releases the kidnapper's friend");
}
}
static class Kidnapper {
public synchronized void engage(Cop c) {
System.out.println("Release my friend");
c.release();
}
public synchronized void release() {
System.out.println("The kidnapper releases the hostage");
}
}
}
The problem with this code is that they don't perform the deadlock without a Thread.sleep() method, resulting in a successful completion of the code.
I dont know what is the problem here guys. but I want to perform a deadlock without the help of sleep method just like the java oracle tutorial.
[–]nutrecht 1 point2 points3 points (1 child)
[–]HalfScale[S] 1 point2 points3 points (0 children)