1: class FileMgmtThread extends Thread { 2: 3: private static final String SYNC = "SYNC" ; 4: 5: private String manageType = ""; 6: 7: public FileMgmtThread (String type) { 8: manageType = type; 9: } 10: 11: public void run() { 12: // synchronized 를 사용함으로써 지정된 객체에 lock이 걸려서 13: // 블록을 수행하는 동안 다른 Thread가 접근할 수 없다. 14: synchronized(SYNC) { 15: try { 16: if ( manageType.equals("READ") ) { 17: File f = new File("Test_367.txt"); 18: if (f.exists()) { // 만약 파일이 존재하면 파일내용을 읽음 19: BufferedReader br = new BufferedReader(new FileReader(f)); 20: br.close(); 21: } 22: } else if ( manageType.equals("DELETE") ) { 23: File f = new File("Test_367.txt"); 24: if (f.exists()) { // 만약 파일이 존재하면 파일을 삭제함 25: f.delete(); 26: } else { 27: ; 28: } 29: } 30: } catch (IOException e) { 31: } 32: } 33: } 34: } 35: 36: public class CWE367 { 37: public static void main(String[] args) { 38: // 파일의 읽기와 파일을 삭제하는 것을 동시에 수행한다. 39: FileMgmtThread fileAccessThread = new FileMgmtThread("READ"); 40: FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE"); 41: fileAccessThread.start(); 42: fileDeleteThread.start(); 43: } 44: }