There is a function to read from the file:

private static String read(File in) { String result= ""; try ( BufferedReader reader = new BufferedReader(new FileReader(in))) { while (reader.ready()) { result= reader.readLine() + "\n"; } } catch(FileNotFoundException e) { System.out.println("File Not Found"); } catch (IOException e) { e.printStackTrace(); } return result; } 

The file is a matrix:

 1 2 3 4 5 6 7 8 9 0 

When reading, I crush the file by "\n" it takes one line and writes to result , then I call this function in the stream that is responsible for reading:

 Thread t_1 = new Thread(new Runnable() { @Override public void run() { str = read(new File("FileName.csv")); } }); t_1.start(); 

How can I make the first line read, the result is written to str , and the line goes to another thread for processing, and the first thread starts reading the second line from the file? Just now it turns out that the last line of the file is fed into str .

  • please explain - michael_best
  • What exactly confuses? - user9431986
  • Well, have you tried? nobody will write a finished program here - michael_best
  • I do not know how to do it, so I ask that what I tried does not work. - user9431986
  • this is called a Producer Consumer; if done with hands, then a thread-safe queue is needed, in which the stream reading the file will add lines and the processing thread will take them out. Runet somehow does not indulge examples, for a seed, you can see this article - zRrr

1 answer 1

Start by creating a class inheriting from Thread

 import java.io.*; public class AsyncTask extends Thread { private String Localstr; private Callback callback; public AsyncTask(Callback callback) { this.callback = callback; } @Override public void run() { read(new File("file.csv")); } private String read(File in) { String result= ""; try ( BufferedReader reader = new BufferedReader(new FileReader(in))) { while (reader.ready()) { result = reader.readLine() + "\n"; if (Localstr == null){ Localstr = result; callback.operation(result); } } } catch(FileNotFoundException e) { System.out.println("File Not Found"); } catch (IOException e) { e.printStackTrace(); } return result; } } 

CallBack interface:

 public interface Callback { void operation(String str); } 

Finally, the call in the main thread:

 AsyncTask task = new AsyncTask(new Callback() { @Override public void operation(String str) { resultInMainThread = str; } }); task.start(); 
  • in this code, callback.operation will be executed in the thread in which it was called - zRrr 5:02
  • @zRrr To the point and return it to the main stream that the author of the question is trying to achieve - Fariz Mamedow
  • not. At best, it will assign the value of str to the field of some class. Replace your assignments with System.out.println( Thread.currentThread().getName() ) and make sure that both the read loop and callback work in the same thread. - zRrr