Simple Deadlock Examples

后端 未结 28 2291
失恋的感觉
失恋的感觉 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:01

    Here's one simple deadlock in Java. We need two resources for demonstrating deadlock. In below example, one resource is class lock(via sync method) and the other one is an integer 'i'

    public class DeadLock {
    
        static int i;
        static int k;
    
        public static synchronized void m1(){
            System.out.println(Thread.currentThread().getName()+" executing m1. Value of i="+i);
    
            if(k>0){i++;}
    
            while(i==0){
                System.out.println(Thread.currentThread().getName()+" waiting in m1 for i to be > 0. Value of i="+i);
                try { Thread.sleep(10000);} catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    
        public static void main(String[] args) {
    
            Thread t1 = new Thread("t1") {
                public void run() {
                    m1();
                }
            };
    
            Thread t2 = new Thread("t2") {
                public void run() {
                    try { Thread.sleep(100);} catch (InterruptedException e) { e.printStackTrace(); }
                    k++;
                    m1();
                }
            };
    
            t1.start();
            t2.start();
        }
    }
    

提交回复
热议问题