Individual thread scheduling in java

I have a long two-part task. The first part is an intensive I / O operation (and there is almost no processor), the second part is an intensive CPU operation. I would have 2 threads performing this task, so that part of the task processor in one thread is tied to the input / output part of this task performed by another thread. In other words, I would like to run the CPU-intensive part in thread #1 , while thread #2 starts the I / O operation and vice versa, so I use the maximum processor and I / O.

Is there any general solution in Java for more than two threads?

+4
source share
4 answers

Create a class that extends Thread. Now create two objects of this class and process the input-output logic and the processor part with two separate functions.

0
source

Take a look at the Executors class:

 //Create a thread pool ExecutorService executorService = Executors.newFixedThreadPool(10); //Launch a new thread executorService.execute(new Runnable() { public void run() { System.out.println("Asynchronous task"); } }); //Try to terminate all the alive threads executorService.shutdown(); 

It can help you: Task completion and planning.

0
source

I do not think that's possible. Thread scheduling is mainly handled by the operating system. The OS decides which thread runs on which logical processor. At the application level, you can only give hints about the OS scheduler, for example, priority, but you cannot force specific planning.

This may be possible with languages ​​like C or C ++ by invoking OS-specific APIs, but at the level of abstraction in Java you cannot force this behavior.

0
source

splitting work into 2 threads is an artificial limitation, and like any limitation associated with art, it can only limit the level of parallelism. If two parts are logically sequential (for example, io operation should precede intensive processor operation to provide data), then they should be executed sequentially in one thread. If you have several independent tasks, they must be performed in different threads. Problems can arise if you have thousands of threads and they eat too much memory. Then you need to separate the work in the tasks and complete these tasks in the thread pool (executing service). This is a more complex approach, as you may need to agree on the beginning of your tasks, but there are no standard tools for this. One of the solutions for coordinating small tasks is the actor’s execution model, but you can’t say in advance if the actor’s model meets your needs.

0
source

Source: https://habr.com/ru/post/1501062/


All Articles