Reputation: 4365
I have a assignment of Java multithreading. I am stuck at a point. There are submitter interface as
public interface ProcessTask<T,U>
{
U processTasksFor(T arg);
}
There are multiple worker threads main task ProcessTask is to split into n independent part of task in thread.
process each splitted task in separate taskProcessThread (for each part separate thread) and return the result to ProcessTask .
my ProcessTask total all the result of the task and print it, result we can consider it as int.
How to define the task structure to simulate this problem. On what area that task can be divided, which concurrency Class should I use to simulate
Upvotes: 0
Views: 1990
Reputation: 14658
There can be 2 options:
1. Use java.util.concurrent.ExecutorService As Java specs says:
An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
So, using an implementation of ExecutorService
you can run all your tasks asynchronously or synchronously in given number of threads. For that you need to create a list of Callable
objects and pass it to invokeAll
method of object of ExecutorService
.
invokeAll
method will return list of list of Future
objects (Each Future object will represent each task, and order is same as you put in Callable
list passed to invokeAll
method) which you can loop total all the result of the task and print it.
You should read all available methods of Executors
class which return different instances of ExecutorService
, so choose the one which suits you.
In this way, you will be able to run your N tasks asynchronously in M threads, and once all the threads are finished you will get list of Future
objects which will give you completion information/status of each task.
try {
List<Callable<Object>> callableList = new ArrayList<Callable<Object>>();
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
//Specify how many threads you want or need to operate. Read other methods of Executors which return different instances of ExecutorService
final ExecutorService service = Executors.newFixedThreadPool(3);
//This will invoke all your N tasks in specified M threads ...
service.invokeAll(callableList);
} catch (InterruptedException e) {
e.printStackTrace();
}
2. Use fork-join framework, if you are running app in multi-processor system (which you should be) and want to take advantage of all available processors. You need to read and go through some example to understand this framework because it is little tricky.
Upvotes: 1
Reputation: 681
I'm not sure if I clearly understood your problem, but have a look at: Executors service and Future to make sure your not reinventing a wheel. Also, have a look at ForkJoin framework.
Upvotes: 0