0 votes
2.8k views
in Java by
java thread deadlock example

1 Answer

0 votes
by

package com.thread.deadlock;

public class A {
    public static int count = 0;
}

package com.thread.deadlock;

public class B {
    public static int count = 0;
}

package com.thread.deadlock;

public class Operation implements Runnable{

    public void incrementAThenB(){
        synchronized (A.class) {
            synchronized (B.class) {

                A.count++;
                B.count++;
            }
        }
    }
    
    public void incrementBThenA(){
        synchronized (B.class) {
            synchronized (A.class) {

                B.count++;
                A.count++;
            }
        }
    }
    
    @Override
    public void run() {
        incrementAThenB();
        incrementBThenA();
    }

}

package com.thread.deadlock;

public class DeadLockMain {

    public static void main(String[] args) {
        Operation operationRunnable = new Operation();
        Thread th1 = new Thread(operationRunnable);
        Thread th2 = new Thread(operationRunnable);
        th1.start();
        th2.start();
        System.out.println("Waiting for threads to complete execution.  .");
        try {
            th2.join();
            th2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Done.");

    }

}

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...