开发者

multithread java syncronization with wait queue

开发者 https://www.devze.com 2023-02-08 15:17 出处:网络
i have a problem about java multithread let\'s see scenario: 1 Thread server (locally, shared memory it\'s just a simulation)

i have a problem about java multithread let's see scenario: 1 Thread server (locally, shared memory it's just a simulation)

class server extends Thead
syncron开发者_StackOverflow社区ized public operation1
synchronized public operation2

.......public operationX

with run method to decide which op1,op2..opX "enable"

3 Thread client -class client extend Thread

client call direct op1,op2..opX to the same server thread (offcourse) created and passed by main..So op1,opX are exectud IN the client server, it's not the server thread to execute it..

so after all Server in the run method decide to enable or disable op1,op2..opX. Client in the run method just call serverreference.op1() ..... serverref.opX()

Ok.. Now suppose all 3 client call op1 which is not enabled by server, they must wait() and then someone else must notify()... But i need to handle these notify FIFO. And notify don't run in fifo wait it's just picked up ONE of suspended thread..

Which utility can i use for handle this situation?

Thx in advice.


You'll probably want to make use of a Blocking Queue. Possibly a Synchronous Queue in your case.

Extend your model to define an operation object (a request). Then the threads would attempt to add their request to the queue. Meanwhile the server thread (if I understand correctly) would attempt to retrieve requests from the queue and handle them.

A synchronous queue is simply a blocking Queue with a size limit of 0. What this means is, each time a thread attempts to add to the queue, it will block until another thread attempts to take an item from that queue. If any other threads do they same they will block as well (there are options for fairness settings).

If there are not operations being submitted, then the server thread will block until one becomes available.

Note, this would cause the operations to be performed in the server thread (main?). If this is not what you want you could additionally hand them off to an Executor to be run on one or more threads. It may sound like a lot of overhead but it's not at all.

JavaDocs:

  • BlockingQueue
  • SynchronousQueue


this may help:

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/LockSupport.html

look at usage sample.


You might be better off using a BlockingQueue instead for the server object blocking each time one thread accesses one of its synchronized methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消