用java 线程写:一个线程生成随机数,另一个线程将产生的随机数写进文件,求大神指教。
展开全部
1.
package chn1;
//生成随机数
import java.util.Random;
public class ReadRandom extends Thread{
private Random ran = new Random();
private double []random;
public void run(){
random = new double[1000];
for(int i = 0;i < random.length;i++){
random[i] = ran.nextDouble();
// System.out.println(random[i]);
}
}
public String getRandom(){
run();
String str = "";
for (int i = 0; i < random.length; i++) {
str += random[i] + "\n";
}
return str;
}
}
2.
//将生成的随机数写入文件
package chn1;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteRandom extends Thread{
ReadRandom rr = new ReadRandom();
File file;
public void run(){
String string = rr.getRandom();
System.out.println(string);
file = new File("E:\\","Example.txt");
try{
if(!file.exists()){
file.createNewFile();
}
FileWriter fWriter = new FileWriter(file);
fWriter.write(string);
fWriter.close();
}
catch (IOException e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
ReadRandom rr = new ReadRandom();
WriteRandom wr = new WriteRandom();
rr.start();
wr.start();
}
}
package chn1;
//生成随机数
import java.util.Random;
public class ReadRandom extends Thread{
private Random ran = new Random();
private double []random;
public void run(){
random = new double[1000];
for(int i = 0;i < random.length;i++){
random[i] = ran.nextDouble();
// System.out.println(random[i]);
}
}
public String getRandom(){
run();
String str = "";
for (int i = 0; i < random.length; i++) {
str += random[i] + "\n";
}
return str;
}
}
2.
//将生成的随机数写入文件
package chn1;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteRandom extends Thread{
ReadRandom rr = new ReadRandom();
File file;
public void run(){
String string = rr.getRandom();
System.out.println(string);
file = new File("E:\\","Example.txt");
try{
if(!file.exists()){
file.createNewFile();
}
FileWriter fWriter = new FileWriter(file);
fWriter.write(string);
fWriter.close();
}
catch (IOException e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
ReadRandom rr = new ReadRandom();
WriteRandom wr = new WriteRandom();
rr.start();
wr.start();
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询