/* * 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. */ /** * DeadlockMethods.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 4-3: * Example 4-3 uses the synchronized statement to demonstrate deadlock. Write * a similar program that causes two threads to deadlock, but use synchronized * methods instead of the synchronized statement. This sort of deadlock is a * little more subtle and harder to detect. * * @author Matthew Feldt * @version 1.0, 2/15/2001 16:37 */ package com.feldt.examples.thread; class DeadlockMethods extends Thread { public synchronized void one(DeadlockMethods dl) { System.out.println("Begin DeadlockMethods.one(): " + this + "."); // simulate work try { Thread.sleep(500); } catch (InterruptedException e) {} System.out.println("DeadlockMethods.one() wants DeadlockMethods.two()."); dl.two(this); System.out.println("End DeadlockMethods.one()."); } public synchronized void two(DeadlockMethods dl) { System.out.println("Begin DeadlockMethods.two(): " + this + "."); // simulate work try { Thread.sleep(500); } catch (InterruptedException e) {} System.out.println("DeadlockMethods.two() wants DeadlockMethods.one()."); dl.one(this); System.out.println("End DeadlockMethods.two()."); } static class Test { static final DeadlockMethods dl1 = new DeadlockMethods(); static final DeadlockMethods dl2 = new DeadlockMethods(); public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { dl1.one(dl2); } }; Thread thread2 = new Thread() { public void run() { dl2.two(dl1); } }; System.out.println("thread1.start()"); thread1.start(); System.out.println("thread2.start()"); thread2.start(); } } }