How to insert an event to the beginning of Event Dispatch Thread queue in java?

前端 未结 3 2100
忘掉有多难
忘掉有多难 2021-02-20 00:45

I already know how Event Dispatch thread works. If there be short and long events in Event Dispatch thread like below, the application can\'t be responsive.

<
3条回答
  •  深忆病人
    2021-02-20 01:13

    My initial thought was

    I do not think we can control the tasks which needs to be picked up by Event Dispatch Thread, but in certain ways we can try to set the priority like below

    SwingUtilities.invokeAndWait(new Runnable() {
      public void run() {
         Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         // The task which need immediate attention.
    }});
    

    Again there is no guarantee that this would be picked up for immediate execution by EDT.

    But the above code is wrong. By the time run gets called it is already executing the tasks. Thanks for the comments Onur.

    So the code below should help.

       EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
       Runnable runnable = new Runnable() {
    
             @Override
             public void run() {
                //My high priority task
             }
       };
       PeerEvent event = new PeerEvent(this, runnable, PeerEvent.ULTIMATE_PRIORITY_EVENT);
       queue.postEvent(event);
    

    But there is one point we need to notice.

        private static final int NUM_PRIORITIES = ULTIMATE_PRIORITY + 1;
    
        /*
         * We maintain one Queue for each priority that the EventQueue supports.
         * That is, the EventQueue object is actually implemented as
         * NUM_PRIORITIES queues and all Events on a particular internal Queue
         * have identical priority. Events are pulled off the EventQueue starting
         * with the Queue of highest priority. We progress in decreasing order
         * across all Queues.
         */
        private Queue[] queues = new Queue[NUM_PRIORITIES];
    
        public EventQueue() {
            for (int i = 0; i < NUM_PRIORITIES; i++) {
                queues[i] = new Queue();
            }
        ....
        }
    

    So if we are setting too many ULTIMATE_PRIORITY tasks, there is no guarantee that the latest task would be executed immediately.

提交回复
热议问题