File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Threads output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threads output" Watch "Threads output" New topic

Threads output

mujtaba ghulam

Joined: May 16, 2009
Posts: 1
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

Joined: Jan 28, 2003
Posts: 4181

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.

I agree. Here's the link:
subject: Threads output
It's not a secret anymore!