Win a copy of Penetration Testing Basics this week in the Security forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads output

mujtaba ghulam
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.
// File
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 ( ){
// connecting FileReader with attribute fileName

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

String line = br.readLine();
while(line != null) {

line = br.readLine();

}catch (Exception e){
} // end run() method



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

}//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
Posts: 4181
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.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic