import java.util.*; import java.io.*; // Somewhat contrived example of deadlock: public class Deadlock { public static void main(String argv[]) { FileSystem a = new FileSystem("A"); FileSystem b = new FileSystem("B"); new Copier(a,b).start(); new Copier(b,a).start(); } } class FileSystem { private String _name; public FileSystem(String name) { _name = name; } public synchronized void copy(FileSystem destination, String filename) { InputStream in = null; /* In real code, = ...*/ ; System.out.println(_name+": Opened " + filename + " for reading, about to write"); destination.writeFile(filename, in); } public synchronized void writeFile(String filename, InputStream in) { // Copy contents of in to file filename System.out.println(_name+": Writing file " + filename); } } // A client thread that just copies the same file // from one filesystem to another, over and over // again. class Copier extends Thread { private FileSystem _from; private FileSystem _to; public Copier(FileSystem fs1, FileSystem fs2) { _from = fs1; _to = fs2; } public void run() { while (true) { _from.copy(_to,"foobar.txt"); } } }