Skip to content

Codes #185

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

public class DeadlockExample {
public static Object lock1 = new Object();
public static Object lock2 = new Object();

public static void main(String[] args) {
    ThreadDemo1 T1 = new ThreadDemo1();
    ThreadDemo2 T2 = new ThreadDemo2();
    T1.start();
    T2.start();
    System.out.println("Main thread finished.");
}

private static class ThreadDemo1 extends Thread {
    public void run() {
        synchronized (lock1) {
            System.out.println("Thread 1: Has lock1");
            try {
                // Sleeping to allow Thread 2 to lock lock2
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 1: Waiting for lock2");
            synchronized (lock2) {
                System.out.println("Thread 1: Has lock1 and lock2");
            }
        }
    }
}

private static class ThreadDemo2 extends Thread {
    public void run() {
        synchronized (lock2) {
            System.out.println("Thread 2: Has lock2");
            try {
                // Sleeping to allow Thread 1 to lock lock1
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 2: Waiting for lock1");
            synchronized (lock1) {
                System.out.println("Thread 2: Has lock2 and lock1");
            }
        }
    }
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions