Simple Deadlock Examples

后端 未结 28 2170
失恋的感觉
失恋的感觉 2020-11-30 16:28

I would like to explain threading deadlocks to newbies. I have seen many examples for deadlocks in the past, some using code and some using illustrations (like the famous 4

相关标签:
28条回答
  • 2020-11-30 17:22

    One of the simple deadlock example I have come across.

    public class SimpleDeadLock {
       public static Object l1 = new Object();
       public static Object l2 = new Object();
       private int index;
       public static void main(String[] a) {
          Thread t1 = new Thread1();
          Thread t2 = new Thread2();
          t1.start();
          t2.start();
       }
       private static class Thread1 extends Thread {
          public void run() {
             synchronized (l1) {
                System.out.println("Thread 1: Holding lock 1...");
                try { Thread.sleep(10); }
                catch (InterruptedException e) {}
                System.out.println("Thread 1: Waiting for lock 2...");
                synchronized (l2) {
                   System.out.println("Thread 2: Holding lock 1 & 2...");
                }
             }
          }
       }
       private static class Thread2 extends Thread {
          public void run() {
             synchronized (l2) {
                System.out.println("Thread 2: Holding lock 2...");
                try { Thread.sleep(10); }
                catch (InterruptedException e) {}
                System.out.println("Thread 2: Waiting for lock 1...");
                synchronized (l1) {
                   System.out.println("Thread 2: Holding lock 2 & 1...");
                }
             }
          }
       }
    }
    
    0 讨论(0)
  • 2020-11-30 17:22

    I found that a bit hard to understand when reading the dining philosophers' problem, deadlock IMHO is actually related to resource allocation. Would like to share a more simple example where 2 Nurse need to fight for 3 equipment in order to complete a task. Although it's written in java. A simple lock() method is created to simulate how the deadlock happen, so it can apply in other programming language as well. http://www.justexample.com/wp/example-of-deadlock/

    0 讨论(0)
  • 2020-11-30 17:22
    package ForkBlur;
    
    public class DeadLockTest {
      public static void main(String args[]) {
    
        final DeadLockTest t1 = new DeadLockTest();
        final DeadLockTest t2 = new DeadLockTest();
    
        Runnable r1 = new Runnable() {
    
            @Override
            public void run() {
                try {
    
                    synchronized (t1) {
                        System.out
                                .println("r1 has locked t1, now going to sleep");
                        Thread.sleep(100);
                        System.out
                                .println("r1 has awake , now going to aquire lock for t2");
                        synchronized (t2) {
                            Thread.sleep(100);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
        };
    
        Runnable r2 = new Runnable() {
    
            @Override
            public void run() {
                try {
    
                    synchronized (t2) {
                        System.out
                                .println("r2 has aquire the lock of t2 now going to sleep");
                        Thread.sleep(100);
                        System.out
                                .println("r2 is awake , now going to aquire the lock from t1");
                        synchronized (t1) {
                            Thread.sleep(100);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
        };
    
        new Thread(r1).start();
        new Thread(r2).start();
      }
    }
    
    0 讨论(0)
  • Let nature explain deadlock,

    Deadlock: Frog vs. Snake

    "I would love to have seen them go their separate ways, but I was exhausted," the photographer said. "The frog was all the time trying to pull the snake off, but the snake just wouldn't let go".

    0 讨论(0)
  • 2020-11-30 17:24

    One example I can think of is the Table, Flashlight, and Batteries scenario. Imagine a flashlight and a pair of batteries placed on top of a table. If you were to walk to this table and grab the batteries while another person has the flashlight you both will be forced to awkwardly stare at each other while waiting for who will first place their item back on the table. This is an example of deadlock. You and the person are waiting for resources but none of you are giving up their resource.

    Similarly, in a program, deadlock occurs when two or more threads (you and the other person) are waiting for two or more locks (flashlight and batteries) to be freed and the circumstances in the program are such that the locks are never freed (you both have one piece of the puzzle).

    If you know java, this is how you can represent this problem:

    import java.util.concurrent.locks.*;
    
    public class Deadlock1 {
    
        public static class Table {
    
            private static Lock Flashlight = new ReentrantLock();
            private static Lock Batteries = new ReentrantLock();        
    
            public static void giveFlashLightAndBatteries() {
                try {
                    Flashlight.lock();
                    Batteries.lock();
                    System.out.println("Lights on");
                } finally {
                    Batteries.unlock();
                    Flashlight.unlock();
                }
            }
    
            public static void giveBatteriesAndFlashLight() {
                try {
                    Batteries.lock();
                    Flashlight.lock();
                    System.out.println("Lights on");
                } finally {
                    Flashlight.unlock();
                    Batteries.unlock();
                }
            }
        }
    
        public static void main(String[] args) {
            // This thread represents person one
            new Thread(new Runnable() {
                public void run() { Table.giveFlashLightAndBatteries(); }
            }).start();
    
            // This thread represents person two
            new Thread(new Runnable() {
                public void run() { Table.giveBatteriesAndFlashLight(); }
            }).start();
        }
    }
    

    If you run this example you will notice that sometimes things work nice and correctly. But sometimes your program will just not print anything. That is because one person has the batteries while another person has the flashlight which prevents them from turning on the flashlight causing a deadlock.

    This example is similar to the example given by the java tutorials: http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html

    Another example is the loop example:

    public class Deadlock2 {
    
        public static class Loop {
            private static boolean done = false;
    
            public static synchronized void startLoop() throws InterruptedException {
                while(!done) {
                    Thread.sleep(1000);
                    System.out.println("Not done");
                }
            }
    
            public static synchronized void stopLoop() {
                done = true;
            }
    
        }
    
        public static void main(String[] args) {
            // This thread starts the loop
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Loop.startLoop();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    
            // This thread stops the loop
            new Thread(new Runnable() {
                public void run() {
                    Loop.stopLoop();
                }
            }).start();
        }
    }
    

    This example can either print 'Not done' over and over or it can never print 'Not done' at all. The first happens because the first thread acquires the class lock and never releases it preventing 'stopLoop' from being accessed by the second thread. And the latest happens because the second thread started before the first thread causing the 'done' variable to be true before the first thread executes.

    0 讨论(0)
  • 2020-11-30 17:24
    public class DeadLock {
    
        public static void main(String[] args) {
            Object resource1 = new Object();
            Object resource2 = new Object();
            SharedObject s = new SharedObject(resource1, resource2);
            TestThread11 t1 = new TestThread11(s);
            TestThread22 t2 = new TestThread22(s);
            t1.start();
            t2.start();
        }
    
    }
    
    class SharedObject {
        Object o1, o2;
        SharedObject(Object o1, Object o2) {
            this.o1 = o1;
            this.o2 = o2;
        }
        void m1() {
            synchronized(o1) {
                System.out.println("locked on o1 from m1()");
                synchronized(o2) { 
                    System.out.println("locked on o2 from m1()");
                }
            }
        }
        void m2() {
            synchronized(o2) {
                System.out.println("locked on o2 from m2()");
                synchronized(o1) { 
                    System.out.println("locked on o1 from m2()");
                }
            }
        }
    }
    
    class TestThread11 extends Thread {
        SharedObject s;
        TestThread11(SharedObject s) {
            this.s = s;
        }
        public void run() {
            s.m1();
        }
    }
    
    class TestThread22 extends Thread {
        SharedObject s;
        TestThread22(SharedObject s) {
            this.s = s;
        }
        public void run() {
            s.m2();
        }
    }
    
    0 讨论(0)
提交回复
热议问题