aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threads output" Watch "Threads output" New topic
Author

Threads output

mujtaba ghulam
Greenhorn

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.
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

Joined: Jan 28, 2003
Posts: 4181
    
  21

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.


Steve
 
Don't get me started about those stupid light bulbs.
 
subject: Threads output