• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads output

 
mujtaba ghulam
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have to perfor the task as follows
Develop a java program using multithreading in which each thread reads the data from a text file and display the data of each file on Console alternatively such that one line from first input file is printed and then one line from another input file is printed and so on.
For this i makes following two file.
ReadFile.java
// File ReadFile.java
import java.io.*;
public class ReadFile implements Runnable{
//attribute used for name of file
String fileName;
// param constructor
public ReadFile(String fn){
fileName = fn;
}
// overriding run method// this method contains the code for file reading
public void run ( ){
try
{
// connecting FileReader with attribute fileName

FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);

String line = br.readLine();
while(line != null) {
Thread.yield();
System.out.println(line);

line = br.readLine();

}
fr.close();
br.close();
}catch (Exception e){
System.out.println(e);
}
} // end run() method
}

2- test.java

import java.io.*;

public class test
{
public static void main (String args[]){

// creating ReadFile objects by passing file names to them
ReadFile first = new ReadFile("file1.txt");
ReadFile second = new ReadFile("file2.txt");
Thread t1 = new Thread(first);
Thread t2 = new Thread(second);

t1.start();
t2.start();
}//End of main
}//End of class

the problem is that whever i run this code it gives different out but sometimes give the required output format.Not as oneline from file1 and one line from line2.
Please help me to solvewhay this happen
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread.yield() does not guarantee that other threads will be executed to a specific point before the current Thread continues.

You will need a more robust synchronization scheme. You should read the java Concurrency tutorial.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic