0810-线程同步题:
启动4个线程,向4个文件A,B,C,D里写入数据,每个线程只能写一个值。
线程1:只写1
线程2:只写2
线程3:只写3
线程4:只写4
4个文件A,B,C,D。
程序运行起来,4个文件的写入结果如下:
A:12341234。。。。
B:23412341。。。。
C:34123412。。。。
D:41234123。。。。
import java.io.*;
class FThread implements Runnable{
int iStart;
String file;
public FThread(int iStart,String file){
this.iStart=iStart;
this.file=file;
}
public void writeFile(){
try{
FileWriter fw=new FileWriter(file);
int wi=iStart;
int count=0;
while(count<10){
if((wi=wi%5)==0){ //注意这里
wi=1;
}
fw.write(new Integer(wi).toString()); //注意这里
wi++;
count++;
}
fw.flush();
fw.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
public void run(){
this.writeFile();
}
}
public class GThread{
public static void main(String[] args){
FThread ft1=new FThread(1,"1.txt");
FThread ft2=new FThread(2,"2.txt");
FThread ft3=new FThread(3,"3.txt");
FThread ft4=new FThread(4,"4.txt");
Thread t1=new Thread(ft1);
Thread t2=new Thread(ft2);
Thread t3=new Thread(ft3);
Thread t4=new Thread(ft4);
t1.start();
t2.start();
t3.start();
t4.start();
}
}