0

i am new to the high level Java.util.Concurrent package , what i am trying to do is read multiple text files at the same time using a thread pool. I need a way to pass the file name as an argument to my implementation of the call method .

Something like this :

public String call (String param)

If there is another way to achieve this i will appreciate your help.

user1203861
  • 1,177
  • 3
  • 15
  • 19
  • 1
    Side comment: what you are doing is I/O bound rather than CPU bound and using multiple threads is unlikely to improve performance. It is actually probably going to be detrimental. – assylias Jul 21 '12 at 16:52
  • each thread will carry much more CPU processing than just reading files – user1203861 Jul 21 '12 at 17:08
  • What you want is basically a function. Java cannot easily model functions as first-class citizens, at least syntactically. Languages that have better support for functional programming may be of interest. – Jed Wesley-Smith Jul 22 '12 at 07:22

1 Answers1

6

When implementing the Runnable interface, add your parameter as a member of the class. And add an initialization of this member in the constructor. Than use it from the run method.

For example:

class ConcurrentFileReader implements Runnable{
   String fileName;

   public ConcurrentFileReader(String fileName){ 
       this.fileName = fileName; 
   }

   public void run(){
       File f = new File(fileName);
      // whatever
   }
}

This pattern is known as a "Method Object"

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Vitaliy
  • 8,044
  • 7
  • 38
  • 66