eventqueue.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 706 行 · 第 1/2 页

JAVA
706
字号
/* * @(#)EventQueue.java	1.46 06/10/10 *  * Copyright  1990-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER *  * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation.  *  * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt).  *  * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA  *  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions.  */package java.awt;import java.awt.event.PaintEvent;import java.awt.event.InvocationEvent;import java.awt.event.KeyEvent;import java.awt.event.ActionEvent;import java.awt.event.FocusEvent;import java.awt.event.InputEvent;import java.awt.event.WindowEvent;import java.awt.ActiveEvent;import java.util.EmptyStackException;import java.lang.reflect.InvocationTargetException;import java.lang.ref.WeakReference;import sun.awt.AppContext;import sun.awt.SunToolkit;/* * Fix for 6370528 - EventQueue race condition or synchronization bug * Both the EventQueue class and EventQueueProxy class were used for * synchronization, which caused the race condition. Fixed by changing * all synchronization using the EventQueueProxy class, since that is * the class that contains the core logic of EventQueue after the * refactoring to fix 6261461 *//** * EventQueue is a platform-independent class that queues events, both * from the underlying peer classes and from trusted application classes. * There is only one EventQueue for each AppContext. * * @author Thomas Ball * @author Fred Ecks * @author David Mendenhall * * @version 	1.67, 02/11/00 * @since 	1.1 */public class EventQueue {    // From Thread.java    private static int threadInitNumber;    private static synchronized int nextThreadNum() {        return threadInitNumber++;    }    private static final int LOW_PRIORITY = 0;    private static final int NORM_PRIORITY = 1;    private static final int HIGH_PRIORITY = 2;    static final int NUM_PRIORITIES = HIGH_PRIORITY + 1; // 6261461    /*     * 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.     */    Queue[] queues = new Queue[NUM_PRIORITIES]; // 6261461    /*     * The next EventQueue on the stack, or null if this EventQueue is     * on the top of the stack.  If nextQueue is non-null, requests to post     * an event are forwarded to nextQueue.     */    private EventQueue nextQueue;    /*     * The previous EventQueue on the stack, or null if this is the     * "base" EventQueue.     */    private EventQueue previousQueue;    private EventDispatchThread dispatchThread;    /*     * Debugging flag -- set true and recompile to enable checking.     */    private final static boolean debug = false;    private WeakReference currentEvent;    private long mostRecentEventTime = System.currentTimeMillis();    private EventQueueProxy proxy = null ; // 6261461    public EventQueue() {        for (int i = 0; i < NUM_PRIORITIES; i++) {            queues[i] = new Queue();        }        String name = "AWT-EventQueue-" + nextThreadNum();        dispatchThread = EventDispatchThread.create(name,                              this.proxy = new EventQueueProxy(this)); // 6261461        dispatchThread.setPriority(Thread.NORM_PRIORITY + 1);        dispatchThread.start();    }    /**     * Post a 1.1-style event to the EventQueue.  If there is an     * existing event on the queue with the same ID and event source,     * the source Component's coalesceEvents method will be called.     *     * @param theEvent an instance of java.awt.AWTEvent, or a     * subclass of it.     */    public void postEvent(AWTEvent theEvent) {        postEventPrivate(theEvent);    }    /**     * Post a 1.1-style event to the EventQueue.  If there is an     * existing event on the queue with the same ID and event source,     * the source Component's coalesceEvents method will be called.     *     * @param theEvent an instance of java.awt.AWTEvent, or a     * subclass of it.     */    final void postEventPrivate(AWTEvent theEvent) {        synchronized (this.proxy) { // 6261461            int id = theEvent.getID();            if (nextQueue != null) {                // Forward event to top of EventQueue stack.                nextQueue.postEventPrivate(theEvent);            } else if (id == PaintEvent.PAINT ||                id == PaintEvent.UPDATE) {                postEvent(theEvent, LOW_PRIORITY);            } else {                postEvent(theEvent, NORM_PRIORITY);            }        }    }    /**     * Posts the event to the internal Queue of specified priority,     * coalescing as appropriate.     */    private void postEvent(AWTEvent theEvent, int priority) {        EventQueueItem newItem = new EventQueueItem(theEvent);        boolean notifyID = (theEvent.getID() == this.proxy.waitForID);//6261461        if (queues[priority].head == null) {            boolean shouldNotify = noEvents();            queues[priority].head = queues[priority].tail = newItem;            // This component doesn't have any events of this type on the            // queue, so we have to initialize the RepaintArea with theEvent            if (theEvent.getID() == PaintEvent.PAINT ||                theEvent.getID() == PaintEvent.UPDATE) {                Object source = theEvent.getSource();                ((Component) source).coalesceEvents(theEvent, theEvent);            }            if (shouldNotify) {                proxy.notifyAll(); // 6261461            }            if (notifyID) {                proxy.notifyAll(); // 6261461            }        } else {            Object source = theEvent.getSource();            // For Component source events, traverse the entire list,            // trying to coalesce events            if (source instanceof Component) {                EventQueueItem q = queues[priority].head;                for (;;) {                    if (q.id == newItem.id && q.event.getSource() == source) {                        AWTEvent coalescedEvent;                        coalescedEvent = ((Component) source).coalesceEvents(q.event, theEvent);                        if (coalescedEvent != null) {                            q.event = coalescedEvent;                            return;                        }                    }                    if (q.next != null) {                        q = q.next;                    } else {                        break;                    }                }            }            // The event was not coalesced or has non-Component source.            // Insert it at the end of the appropriate Queue.            if (theEvent.getID() == PaintEvent.PAINT ||                theEvent.getID() == PaintEvent.UPDATE) {                // This component doesn't have any events of this type on the                // queue, so we have to initialize the RepaintArea with theEvent                ((Component) source).coalesceEvents(theEvent, theEvent);            }            queues[priority].tail.next = newItem;            queues[priority].tail = newItem;            if (notifyID) {                proxy.notifyAll(); // 6261461            }        }    }    /**     * @return whether an event is pending on any of the separate Queues     */    private boolean noEvents() {        for (int i = 0; i < NUM_PRIORITIES; i++) {            if (queues[i].head != null) {                return false;            }        }        return true;    }    /**     * Remove an event from the EventQueue and return it.  This method will     * block until an event has been posted by another thread.     * @return the next AWTEvent     * @exception InterruptedException     *            if another thread has interrupted this thread.     */    public AWTEvent getNextEvent() throws InterruptedException {        return this.proxy.getNextEvent(); // 6261461    }    /**     * Return the first event on the EventQueue without removing it.     * @return the first event     */    public AWTEvent peekEvent() {        synchronized (this.proxy) { // 6370528        for (int i = NUM_PRIORITIES - 1; i >= 0; i--) {            if (queues[i].head != null) {                return queues[i].head.event;            }        }        return null;        }    }    /**     * Return the first event with the specified id, if any.     * @param id the id of the type of event desired.     * @return the first event of the specified id     */    public AWTEvent peekEvent(int id) {        synchronized (this.proxy) { // 6370528        for (int i = NUM_PRIORITIES - 1; i >= 0; i--) {            EventQueueItem q = queues[i].head;            for (; q != null; q = q.next) {                if (q.id == id) {                    return q.event;                }            }        }        return null;        }    }    /**     * Dispatch an event. The manner in which the event is     * dispatched depends upon the type of the event and the     * type of the event's source     * object:     * <p> </p>     * <table border>     * <tr>     *     <th>Event Type</th>     *     <th>Source Type</th>     *     <th>Dispatched To</th>     * </tr>     * <tr>     *     <td>ActiveEvent</td>     *     <td>Any</td>     *     <td>event.dispatch()</td>     * </tr>     * <tr>     *     <td>Other</td>     *     <td>Component</td>     *     <td>source.dispatchEvent(AWTEvent)</td>     * </tr>     * <tr>     *     <td>Other</td>     *     <td>MenuComponent</td>     *     <td>source.dispatchEvent(AWTEvent)</td>     * </tr>     * <tr>     *     <td>Other</td>     *     <td>Other</td>     *     <td>No action (ignored)</td>     * </tr>     * </table>     * <p> </p>     * @param theEvent an instance of java.awt.AWTEvent, or a     * subclass of it.     */    protected void dispatchEvent(AWTEvent event) {        Object src = event.getSource();        if (event instanceof ActiveEvent) {            // This could become the sole method of dispatching in time.            ((ActiveEvent) event).dispatch();        } else if (src instanceof Component) {            ((Component) src).dispatchEvent(event);        } /*         else if (src instanceof MenuComponent) {         ((MenuComponent)src).dispatchEvent(event);         }          */ else {            System.err.println("unable to dispatch event: " + event);        }    }    /**     * Replace the existing EventQueue with the specified one.     * Any pending events are transferred to the new EventQueue     * for processing by it.     *     * @param an EventQueue (or subclass thereof) instance to be used.     * @see      java.awt.EventQueue#pop     */    public void push(EventQueue newEventQueue) {        synchronized (this.proxy) { // 6370528        if (debug) {            System.out.println("EventQueue.push(" + newEventQueue + ")");        }        if (nextQueue != null) {            nextQueue.push(newEventQueue);            return;        }        synchronized (newEventQueue.proxy) { // 6370528            // Transfer all events forward to new EventQueue.            while (peekEvent() != null) {                try {                    newEventQueue.postEventPrivate(getNextEvent());                } catch (InterruptedException ie) {                    if (debug) {                        System.err.println("interrupted push:");                        ie.printStackTrace(System.err);                    }                }            }            newEventQueue.previousQueue = this;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?