0810-线程同步题

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();			
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值