package fileLock; import java.io.*; public class Flock_test { static final String resource_name[]={"plane_reserve","hotel_reserve"}; static final int PLANE =0; static final int HOTEL =1; static final int MAX_RESOURCE = 2; FileResource resource[]; // we con't need this, but sometime we will use it... /** * @param args * @throws IOException * * Test routine for FileResoruce * * javac fileLock/*.java * echo 1 > plane_reserve * echo 1 > hotel_reserve * java fileLock/Flock_test Adam & java file/Flock_test1 Betty * You have to create Flock_test1 or try some other method to * create dead lock situation. * */ Flock_test() { resource = new FileResource[MAX_RESOURCE]; } public static void main(String args[]) throws IOException, FileNotFoundException, InterruptedException { Flock_test self = new Flock_test(); // We need an instance to make wait(int) happy. It is better than using static class. // For example, we can extend this example using Thread. self.run(args); } public synchronized void run(String args[]) throws IOException, InterruptedException { if (args[0]==null) { System.out.println("Please specify my name in command line."); return; } String myself = args[0]; FileResource plane = resource[PLANE] = new FileResource(resource_name[PLANE]); FileResource hotel = resource[HOTEL] = new FileResource(resource_name[HOTEL]); plane.open_with_lock(); if (!plane.reserve()) return; plane.release(); System.out.println(plane.resource_name()+" is reserved by "+myself+"."); wait(10); hotel.open_with_lock(); if (!hotel.reserve()) return; hotel.release(); System.out.println(hotel.resource_name()+" is reserved "+myself+"."); } }