I want to implement a class that will manage the threads in my library.

The bottom line is that I need to create methods in other classes that run in parallel.

Suppose I want to implement a method that processes a list in several threads and returns a map.

For this, in the method I am going to create an object of the class threads_manager and transfer to it the data processing function and additional information (number of threads, etc.).

Next, in the constructor, create n class objects, on the next Thread and then start them.

Question: Do I reason correctly and how can I transfer the method to the constructor so that I can transfer it to another constructor?

I apologize in advance, I'm new to java and C ++ is still sitting tight in my head.

  • In java methods are not passed anywhere. You need to make an object with the necessary methods and pass it. And at the destination, refer to the methods of this object. In Java 8, the task is somewhat simplified if a functional interface is used as the "parameter method". Then, as an object, you can pass a lambda, which slightly reduces the number of lines of code to be dialed. - Sergey
  • You can read about dyambda here for example habrahabr.ru/post/224593 Even there are such concepts as references to methods and constructors (but this is only syntax sugar) - Sergey
  • @Sergey but I want to make it so that with the help of my manager I can parallelize any function. With the same parameters parameters at least. There are no such patterns in Java? - toodef
  • Everything can be parallelized - Sergey
  • @Sergey yes, but how to do it with a single class? - toodef pm

1 answer 1

You cannot send a method directly, you can pass a Functional Interface (Interface has exactly one abstract method), there are several options in Java itself: Function (Clicks one argument, returns value), Consumer (Accepts one argument, returns nothing), Producer (Does not accept nothing, returns value). You can also write your own. For example, one of my:

 public static interface CommandAction { public void performCommand(Message msg, String[] args, Guild giuld); } 

After that, such an interface can be transferred in different ways:
Anonymous class:

 new CommandAction() { public void perfromCommand(Message msg, String[] args, Guild guild) { //SomeCode } } 

Lambda expression:

 (msg, args, guild) -> { //SomeCode } 

Method Reference:

 public static void SomeMethod(Message msg, String[] args, Guild guild) { //SomeCode } //В вызове SomeClass::SomeMethod