多个线程对一个同一个文件进行写操作的时候是否需要同步呢?
例如FileWriter类,多个线程都创建了一个FileWriter对象像同一个文件中追加数据,我并没有使用同步代码块似乎并没有出错

解决方案 »

  1.   

    放在同步代码块里,或者用哪个新的Lock类,不然大批量操作的时候问题会有的
      

  2.   

    好像是管道流吧   PipedInputStream   
                     PIpedOutputStream
    io当中涉及多线程的流import java.io.*;//管道流,和多线程技术相关的ioclass Reade implements Runnable
    {
    private PipedInputStream in; Reade(PipedInputStream in)
    {
    this.in = in;
    }
    public void run()
    {
    try
    {
    byte[] buf = new byte[1024]; int len = 0; while((len=in.read(buf))!=-1)
    {
    System.out.println(new String(buf,0,len));
    }
    }
    catch (IOException e)
    {
    throw new RuntimeException("管道读取流失败");
    }
    finally
    {
    try
    {
    if(in!=null)
    in.close();
    }
    catch (IOException e)
    {
    throw new RuntimeException("管道读取流关闭失败");
    }
    }
    }
    }class Write implements Runnable
    {
    private PipedOutputStream out; Write(PipedOutputStream out)
    {
    this.out = out;
    }
    public void run()
    {
    try
    {
    out.write("dsaldjkasl".getBytes());
    }
    catch (IOException e)
    {
    throw new RuntimeException("管道输出流失败");
    }
    finally
    {
    try
    {
    if(out!=null)
    out.close();
    }
    catch (IOException e)
    {
    throw new RuntimeException("管道输出流关闭失败");
    }
    }
    }
    }class  PipedStreamDemo
    {
    public static void main(String[] args) 
    {
    PipedInputStream in = null;
    PipedOutputStream out = null; try
    {
    in = new PipedInputStream();
    out = new PipedOutputStream();
       //将两个管道流连接
       in.connect(out);    new Thread(new Reade(in)).start();
       new Thread(new Write(out)).start();
    }
    catch (IOException e)
    {
    throw new RuntimeException("管道流错乱");
    }
    }
    }
      

  3.   

    NIO的话死的更惨,你这个解答在特殊时候不适用啊