用synchronized关键字
将文件操作用
synchronized(this)
{
   文件操作。
}
包含起来就OK了。

解决方案 »

  1.   

    我的建议是你多个线程用一个file对象,在用文件的时候对file对象进行同步,修改代码如下:
    class SimpleThread extends Thread
    {
      private int countDown = 5;
      private static int threadCount = 0;
      private static File f ;
      private int threadNumber = ++threadCount;
      public SimpleThread() {    System.out.println("Making "+threadNumber);
        if(f!=null)
        {
          f = new File("test.property");
        }
          if (!f.exists()) {
            System.err.println("Error: property file not found!");
            return ;
          }
      }  public void run() {
        while(true) {
          System.out.println("Thread "+ threadNumber + "("+countDown + ")");
          if (--countDown ==0) {
            return;
          }
          else {
            try {
              getNewDevNo("firewall");        }
            catch (Exception ex) {
              System.out.println(ex);
            }                
          }
        }
      }  public static void main(String[] args) throws Exception
      {
        for (int i=0; i<5; i++) {
          new SimpleThread().start();
        }
        System.out.println ("All Threads Started");  }  private synchronized void getNewDevNo(String devType) throws Exception
      {    Properties prop = new Properties();
        synchronized(f)
        {
          FileInputStream fileis = new FileInputStream(f);
          prop.load(fileis);
          fileis.close();
        }    int newDevNo = 0;
        String oldDevNo = prop.getProperty(devType);
        if (oldDevNo == null) {
          throw new NoSuchElementException();
        }    newDevNo = Integer.parseInt(oldDevNo) + 1;
        synchronized(f)
        {
          prop.setProperty(devType,String.valueOf(newDevNo));      FileOutputStream fileos = new FileOutputStream(f);
          prop.store(fileos,"DevNo");
          fileos.close();
        }
        System.out.println ("Found new device, number is: "+newDevNo);        
      }    
    }