How can I make ThreadPoolExecutor command wait if there's too much data it needs to work on?

后端 未结 4 1419
我在风中等你
我在风中等你 2020-12-14 04:45

I am getting data from a queue server and I need to process it and send an acknowledgement. Something like this:

while (true) {
    queueserver.get.data
             


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 04:53

    first, i think your attitude is wrong because what you did in your pseudo code is busy waiting, you should read through the Concurrency tutorial from java toturial http://docs.oracle.com/javase/tutorial/essential/concurrency/

    ignoring that, ill offer you a solution with the busy wait (which is not recommanded):

         ExecutorService e1 =  Executors.newFixedThreadPool(20);
         while (true) {
              if (!serverq.isEmpty() && !myq.isFull()) myq.enq(serverq.poll());
              if (!myq.isEmpty()) e1.execute(myq.poll());
         }
    

    NOTES:

    1.make sure your myq is synchronized, as said in the other answers. you can extend some blocking queue to make sure the synchronization is correct.

    2.you implement a runnable class which does what you exepct from the server in an iteration of service, those runnables have to get myq as a parameter to the constructor and save it as global variable.

    3.myq gets the runnables, that in the end of its run method, you must make sure the runnable deletes itself from myq.

提交回复
热议问题