1

Suppose four threads have to do tasks. Each thread has to do a single unit work. how to know which thread has finished its work to assign it next work.

actually, I have to use 4 threads and each thread has to copy one column of a 2d array into 1d array..

Edit : Without using Threadpool. Many Thanks.

RISHAV KUMAR
  • 176
  • 3
  • 14
  • 2
    Have the threads pull the work from a shared (synchronized) work queue, and loop all the time, pulling the next item from the queue? – JP Moresmau Feb 22 '16 at 20:17
  • actually, I have to use 4 threads and each thread has to copy one column of a 2d array into 1d array.. I have updated the question. Thanks. – RISHAV KUMAR Feb 22 '16 at 20:21

1 Answers1

0

Since you're submitting tasks to threads, the same effect can be accomplished using this:

    ExecutorService es = Executors.newFixedThreadPool (4);

    for (int i=1; i<=TOTAL_TASKS; i++) {
        es.submit (new Runnable() {
            @Override
            public void run () {
                // Do work here!
            }
        });
    }
Jose Cifuentes
  • 596
  • 6
  • 21
  • could it be done without using Threadpool? Thanks. – RISHAV KUMAR Feb 22 '16 at 20:35
  • Didn't know you had that specific constraint. So, without using a ThreadPool one option is to do what JP Moresmau suggest -- using a work queue, and pull entries from it that allow your thread code to process the next work item. Wanted to clarify: The threads are destroyed once they finish execution, so you simply cannot let run() method finish to its end and expect to assign more work to a thread, since it has already died. – Jose Cifuentes Feb 22 '16 at 20:41
  • Expanding on what @JoseCifuentes said, you should use a blocking work queue to avoid Thread termination. – drakyoko Feb 22 '16 at 22:26