2014-02-14 101 views
1

我写了一个Runnable类Java的可运行文件IO

private static class Processing implements Runnable { 
    private static File file; 
    private static byte[] message; 
    public Processing (File f, byte[] m){ 
     this.file = f; 
     this.message = m; 
    }  
    public void run(){ 
     WriteToFile(file , message); 
          ... other processing.... 
    } 

private static void WriteToFile(File f , byte[] msg){ 
    FileOutputStream fs = null; 
    try { 
     fs = new FileOutputStream(f) ; 
     fs.write( msg); 
     fs.flush(); 
     fs.close(); 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 

} 

在主类

public class MainClass{ 
    public void somemethod(){ 
     .... 
     (new Thread(new Processing (<somefile> , <somebytes>))).start(); 
     .... 
    } 

} 

我的问题是

  1. 是这个方法正确吗?我的愿望是提高文件io(在 WriteToFile方法),因为MainClass被超过1000个 用户调用。
  2. 如何在代码中模拟1000个用户?是

    for (int i = 0 ; i<1000 ...){ 
        (new Thread(new Processing (<somefile> , <somebytes>))).start(); 
    } 
    

感谢

回答

3
  • 对于Q1:看起来不错,但请记住,你总是在finally块关闭流,因为写入操作可能会失败,这可能会使您文件句柄摇晃。

  • 对于Q2:只要你没有写入1000个线程的同一个文件,那么你就需要考虑线程的安全性。

3

我同意Neeveks的回答,但我可以看到两个额外的问题。

1)filemessage应该是实例变量,不应该是静态的。将它们设置为静态意味着您一次只能管理一个文件和一条消息。

2)方法的名称以Java中的小写字母开头。请将WriteToFile重命名为writeToFile。这不是一个编程问题,但它有助于阅读你的代码。

1

看起来不错,你可以尝试内存映射文件,如果数据很大。您可以从已有的关于写入文件here的答案中获得一些参考。