import java.lang.Thread; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.io.*; import java.util.*; import java.text.*; public class LockedFile { private ReentrantReadWriteLock theLock = new ReentrantReadWriteLock(true); private void testLocking() { theWriter w1 = new theWriter("A"); new Thread(w1).start(); } public static void main(String[] args) { LockedFile lv = new LockedFile(); lv.testLocking(); } private class theWriter implements Runnable { private String name; public theWriter(String theName) { name = theName; } public void run() { try { theLock.writeLock().lock(); // open file and write try { PrintWriter output = new PrintWriter("file.txt"); Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("HH:mm:ss SSS"); output.println("The Writer " + name + " with the value "+ ft.format(dNow)); output.close(); } catch (java.io.FileNotFoundException e) {} try { Thread.sleep(2000); } catch (InterruptedException e) {} } finally { theLock.writeLock().unlock(); } } } }