/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * Deadlock.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 4-2: * Example 4-3 demonstrates how deadlock acan occur when two threads each * attempt to obtain a lock held by the other. Modify the example to create * deadlock among three threads, where each thread is trying to acquire a lock * held by one of the other threads. * * @author Matthew Feldt * @version 1.0, 02/15/2001 16:37 */ package com.feldt.examples.thread; public class Deadlock { public static void main(String[] args) { // resource objects to locks on final Object resource1 = "resource1"; final Object resource2 = "resource2"; final Object resource3 = "resource3"; // first thread - it tries to lock resource1 then resource2 Thread t1 = new Thread() { public void run() { // lock resource1 synchronized(resource1) { System.out.println("Thread 1: locked resource 1"); // pause... try { Thread.sleep(50); } catch (InterruptedException e) {} // attempt to lock resource2 System.out.println("Thread 1: wants resource 2"); synchronized(resource2) { System.out.println("Thread 1: locked resource 2"); } } } }; // second thread - it tries to lock resource2 then resource3 Thread t2 = new Thread() { public void run() { // lock resource2 synchronized(resource2) { System.out.println("Thread 2: locked resource 2"); // pause... try { Thread.sleep(50); } catch (InterruptedException e) {} System.out.println("Thread 2: wants resource 3"); synchronized(resource3) { System.out.println("Thread 2: locked resource 3"); } } } }; // third thread - it tries to lock resource3 then resource1 Thread t3 = new Thread() { public void run() { // lock resource3 synchronized(resource3) { System.out.println("Thread 3: locked resource 3"); // pause... try { Thread.sleep(50); } catch (InterruptedException e) {} System.out.println("Thread 3: wants resource 1"); synchronized(resource1) { System.out.println("Thread 3: locked resource 1"); } } } }; // start all three threads - should deadlock and program will never exit t1.start(); t2.start(); t3.start(); } }