四条线程同时往四个不同文件添加内容

package net.jxatei.jsj.test;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;


public class IOAndThread implements Runnable
{
public static void main ( String[] args )
{
IOAndThread ioThread = new IOAndThread ();
new Thread ( ioThread ).start ();
new Thread ( ioThread ).start ();
new Thread ( ioThread ).start ();
new Thread ( ioThread ).start ();
}


@Override
public void run ()
{
for ( int i = 1 ; i <= 4 ; i ++ )
{
switch ( i % 4 )
{
case 1 :
fun1 ();
break;
case 2 :
fun2 ();
break;
case 3 :
fun3 ();
break;
case 0 :
fun4 ();
break;


default :
break;
}
}


}


private static void fun1 ()
{
try
{
BufferedOutputStream bos = new BufferedOutputStream (
new FileOutputStream ( new File ( "files/F1.txt" ) , true ) );
byte[] buff = "ABCD\n".getBytes ();
bos.write ( buff , 0 , buff.length );
bos.flush ();
bos.close ();
System.out.println ( "F1文件写入成功" );
}
catch ( Exception e )
{


e.printStackTrace ();
}
}


private static void fun2 ()
{
try
{
BufferedOutputStream bos = new BufferedOutputStream (
new FileOutputStream ( new File ( "files/F2.txt" ) , true ) );
byte[] buff = "BCDA\n".getBytes ();
bos.write ( buff , 0 , buff.length );
bos.flush ();
bos.close ();
System.out.println ( "F2文件写入成功" );
}
catch ( Exception e )
{


e.printStackTrace ();
}
}


private static void fun3 ()
{
try
{
BufferedOutputStream bos = new BufferedOutputStream (
new FileOutputStream ( new File ( "files/F3.txt" ) , true ) );
byte[] buff = "CDBA\n".getBytes ();
bos.write ( buff , 0 , buff.length );
bos.flush ();
bos.close ();
System.out.println ( "F3文件写入成功" );
}
catch ( Exception e )
{


e.printStackTrace ();
}
}


private static void fun4 ()
{
try
{
BufferedOutputStream bos = new BufferedOutputStream (
new FileOutputStream ( new File ( "files/F4.txt" ) , true ) );
byte[] buff = "DABC\n".getBytes ();
bos.write ( buff , 0 , buff.length );
bos.flush ();
bos.close ();
System.out.println ( "F4文件写入成功" );
}
catch ( Exception e )
{


e.printStackTrace ();
}
}
}

猜你喜欢

转载自blog.csdn.net/JavaMyDream/article/details/80903375