多个线程操作同一个文件是否需要同步 多个线程对一个同一个文件进行写操作的时候是否需要同步呢?例如FileWriter类,多个线程都创建了一个FileWriter对象像同一个文件中追加数据,我并没有使用同步代码块似乎并没有出错 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 放在同步代码块里,或者用哪个新的Lock类,不然大批量操作的时候问题会有的 好像是管道流吧 PipedInputStream PIpedOutputStreamio当中涉及多线程的流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("管道流错乱"); } }} NIO的话死的更惨,你这个解答在特殊时候不适用啊 请教了,SSL双向认证??? 学习JAVA 建立JTree 问题? JAVA Calendar 类 setFirstDayOfWeek 方法详解 截字符串问题 急呀.懂java有谁能帮我一下. 怎样可以重设表格的列宽??谢谢大家的帮忙了 (路人甲)List->Arrays 类的加载和对象的创建 Java io流的问题 打开选择文件窗口过滤条件的顺序问题 关于java线程的问题
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("管道流错乱");
}
}
}