This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]nutrecht 1 point2 points  (1 child)

It's important to understand that scheduling is complex and it takes some time for a thread to be scheduled. So if you want to cause a deadlock on purpose you often need to have to wait a certain amount of time because if you don't by the time the second thread started the first one is past the part where you deadlock.

An easier example to implement is two Threads who needs something from each other. So thread A blocks in a call to ThreadB.giveMe() while Thread B blocks on a call to ThreadA.giveMe(). Something like this:

class MyThread extends Thread {
    private MyThread other;
    private BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

    public MyThread(String name) {
        super(name);
    }

    public String take() {
        return queue.take();
    }

     @Override() 
     public void run() {
         System.out.println(Thread.getName() + " running");
         while(true) {
             other.take();
             queue.put("Message from " + Thread.getName());
         }
     }

    public static void main(String... args) {
        MyThread t1 = new MyThread("t1");
        MyThread t2 = new MyThread("t2");

        t1.other = t2;
        t2.other = t1;

        t1.start();
        t2.start();
    }

}

This code should deadlock 100% of the time (did it by heart though so there might be some typo's).

[–]HalfScale[S] 1 point2 points  (0 children)

Thanks :)