aspose file tools*
The moose likes Threads and Synchronization and the fly likes Stack in threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Stack in threads" Watch "Stack in threads" New topic
Author

Stack in threads

Santosh Kumar Nayak
Ranch Hand

Joined: Aug 02, 2011
Posts: 95
Scenario:-
There are 2 threads A and B

There are tasks like T1,T2,T3,T4 ....T10

How to put the logic such that A processes T1 , then B processes T2, then A processes T3 , then B processes T4 and so on...


I had an idea of using a Stack and both threads processing the tasks. Any other Approach ?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

A Queue is more often used since the producers (those putting the task to be done into a collection) and the consumers (those doing the tasks) don't have to compete for the same side of the collection and to prevent tasks from becoming stale. A stack, they would both be accessing the top of the stack, for a queue the producers add to the end and the consumers take from the front.

But in practice, using an ExecutorService (like the ThreadPoolExecutor) will do this sort of queuing and distribution for you, and also maintains the threads. So you should probably just consider using one of those.


Steve
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Steve Luke wrote:
But in practice, using an ExecutorService (like the ThreadPoolExecutor) will do this sort of queuing and distribution for you, and also maintains the threads. So you should probably just consider using one of those.


And executors generally does what is most efficient, and not exact fine grain control. For example...

Santosh Kumar Nayak wrote:Scenario:-
There are 2 threads A and B

There are tasks like T1,T2,T3,T4 ....T10

How to put the logic such that A processes T1 , then B processes T2, then A processes T3 , then B processes T4 and so on...


If an executor has two threads (say A and B), then A will get T1 and B will get T2. However, if thread B finishes processing first, it will not wait for thread A, it will go get the next task, T3, and process that. By default, there won't be interlacing of threads and tasks.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Luan Cestari
Ranch Hand

Joined: Feb 07, 2010
Posts: 163

You can create a queue to each worker thread. The most complex part would be the thread that have to push the tasks to those queues, that could be another thread with a list of those queues and it could analyze the task to see which queue to use.


Please, visit me for some cool tech post at www.ourdailycodes.com
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Stack in threads