1
我可能会在这里问一个重复的问题。 但仍然无法解决我的问题。在java中使用多线程在文件中写入值
我试着为下面的问题找到答案。
编写一个程序来创建2个主题。线程1将在每次输入输出文件后以1秒的延迟写入数字1到10。线程2将在每次输入到同一输出文件后以两秒的延迟写入数字1到10。
重量我做
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class Thread1 extends Thread
{
public void run()
{
ThreadSample threadSample = new ThreadSample();
try {
threadSample.printer(500);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Thread2 extends Thread
{
public void run()
{
ThreadSample threadSample = new ThreadSample();
try {
threadSample.printer(1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*{
try {
for(int i=0;i<10;i++){
System.out.println(this.getName()+" "+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}
}
public class ThreadSample extends Thread{
public void printer(int j) throws IOException{
FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt");
//f.getAbsoluteFile();
BufferedWriter br = new BufferedWriter(f);
synchronized(this){
try {
FileWriter fw=new FileWriter("C:\\Users\\BK00354083\\Desktop\\sample.txt");
for(int i=0;i<10;i++){
System.out.println(this.getName()+" "+i);
br.write("values"+ i);
br.newLine();
Thread.sleep(j);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
br.close();
}
}
}
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}
但写一个线程值转换成文件。 所以我改变了我的代码像下面
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class Thread1 extends Thread
{
public void run()
{
FileWriter f;
try {
f = new FileWriter("C:\\Users\\Desktop\\sample.txt");
BufferedWriter br = new BufferedWriter(f);
synchronized(this){
try {
for(int i=0;i<10;i++){
System.out.println(this.getName()+" "+i);
br.write("values"+ i);
br.newLine();
Thread.sleep(500);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
br.close();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class Thread2 extends Thread
{
public void run()
{
FileWriter f;
try {
f = new FileWriter("C:\\Users\\Desktop\\sample.txt");
BufferedWriter br = new BufferedWriter(f);
synchronized(this){
try {
for(int i=0;i<10;i++){
System.out.println(this.getName()+" "+i);
br.append("values"+ i);
br.newLine();
Thread.sleep(500);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}finally {
br.close();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class ThreadSample extends Thread{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}
即使在使用时也只写了相同的线程2的值 任何帮助.. !!!
我没有得到完整的问题。你是从一个线程获取输出还是在同一个文件中获得两个线程? –
它是仅写入线程2值还是先线程2值,然后线程1值?是否有线程1抛出异常? –
@ Ravindra babu 两个线程应写入同一个文件 – Sana