• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stack in threads

 
Santosh Kumar Nayak
Ranch Hand
Posts: 143
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 20882
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Luan Cestari
Ranch Hand
Posts: 163
C++ Redhat Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic