/** * a simple deadlock example * with two processes sharing two mutex resources * @author mh, following Magee&Kramer, ch6, p.109 * */ class Resource { private boolean free = true; private String name; public Resource (String name) { this.name = name; } public synchronized void get(String user) { try { while (! free) { wait(); } } catch (InterruptedException e) {} free = false; System.out.println(name + " is taken by " + user); } public synchronized void put(String user) { free = true; notifyAll(); System.out.println(name + " is returned by " + user); } } // class Resource //*********************************************************** class Process implements Runnable { private Resource resource1, resource2; private String name; public Process (String name, Resource r1, Resource r2) { resource1 = r1; resource2 = r2; this.name = name; } public void run() { Simulate.doSomething(); resource1.get(name); Simulate.doSomething(); resource2.get(name); System.out.println(name + " is having both resources"); resource1.put(name); resource2.put(name); } } // class User //*********************************************************** public class Deadlock { public static void main (String[] argv) { Resource print = new Resource("PRINTER"); Resource scan = new Resource("SCANNER"); Process p = new Process("P", print, scan); Process q = new Process("Q", scan, print); (new Thread(p)).start(); (new Thread(q)).start(); } } // class Deadlock //************************************************************* class Simulate { public static void doSomething() { if (Math.random()<0.5) { try { Thread.sleep(200);} catch(InterruptedException e){}; //used instead of Thread.yield() to ensure portability } } } // class Simulate //***************************************************************