⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadsexample.java

📁 MPICH是MPI的重要研究,提供了一系列的接口函数,为并行计算的实现提供了编程环境.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        }    }    catch (InterruptedException e) {        updateStatus(0);        return "Interrupted";      }    return "All Done"; }</pre>This method does what any time consuming operation should: itperiodically lets the user know that it's making progress.  The<code>updateStatus()</code> method queues a Runnable for the eventdispatching thread (remember: don't do GUI work on other threads) whichupdates a progress bar.  To start the worker thread running, the<code>Action</code> for the "Start" menu item creates a SwingWorker thatcalls <code>doWork()</code>:<pre>worker = new SwingWorker() {    public Object construct() {        return doWork();    }    public void finished() {        startAction.setEnabled(true);        abortAction.setEnabled(false);        statusField.setText(get().toString());    }};</pre>This statement immediately forks a thread that runs<code>SwingWorker.construct()</code>.  The <code>finished()</code>method runs after the <code>construct()<code> method returns.  TheSwingWorker class runs the <code>finished()</code> method on the eventdispatching thread so it's safe to do GUI work, e.g. setting the statustext field.  In this case we're just reenabling the startmenu item and disabling the abort menu item when the workerthread is finished.<p>If you try running the example you'll see that you can abort the"Start" action at any time and that only one of the "Start" and"Abort" menu items are enabled at a time so that it's not possible to abort when nothings running and similarly one canonly start one operation at a time.  @end Example1 */class Example1 extends JPanel{    JProgressBar progressBar = new JProgressBar();    JLabel statusField = new JLabel("Select 'Start' Action Menu Item to Begin");    SwingWorker worker;    /**     * When the worker needs to update the GUI we do so by queuing     * a Runnable for the event dispatching thread with      * SwingUtilities.invokeLater().  In this case we're just     * changing the progress bars value.     */    void updateStatus(final int i) {	Runnable doSetProgressBarValue = new Runnable() {	    public void run() {		progressBar.setValue(i);	    }	};	SwingUtilities.invokeLater(doSetProgressBarValue);    }        /**     * This method represents the application code that we'd like to      * run on a separate thread.  It simulates slowly computing      * a value, in this case just a string 'All Done'.  It updates the      * progress bar every half second to remind the user that     * we're still busy.     */    Object doWork() {	try {	    for(int i = 0; i < progressBar.getMaximum(); i++) {		updateStatus(i);		Thread.sleep(500);	    }	}	catch (InterruptedException e) {	    updateStatus(0);	    return "Interrupted";  // SwingWorker.get() returns this	}	return "All Done";         // or SwingWorker.get() returns this    }    /**     * This action, called from the "Start" menu item, effectively      * forks the thread that does the work. We use Action.setEnabled()     * to ensure that only the start item can't be selected until     * the worker has either finished or been aborted.  Note also     * that the SwingWorker.finished() method runs on the event dispatching     * thread, so we don't have to bother with SwingUtilities.invokeLater().     */    Action startAction = new AbstractAction("Start") {	public void actionPerformed(ActionEvent event) {	    startAction.setEnabled(false);	    abortAction.setEnabled(true);	    statusField.setText("Working...");	    /* Constructing the SwingWorker() causes a new Thread	     * to be created that will call construct(), and then	     * finished().  Note that finished() is called even if	     * the worker is interrupted because we catch the	     * InterruptedException in doWork().	     */	    worker = new SwingWorker() {		public Object construct() {		    return doWork();		}		public void finished() {		    startAction.setEnabled(true);		    abortAction.setEnabled(false);		    statusField.setText(get().toString());		}	    };	}    };    /**     * This action, called from the "Abort" menu item, interrupts     * the worker thread which is running this.doWork().  Note that     * the doWork() method handles InterruptedExceptions cleanly.     */    Action abortAction = new AbstractAction("Abort") {	public void actionPerformed(ActionEvent event) {	    abortAction.setEnabled(false);	    worker.interrupt();	    startAction.setEnabled(true);	}    };    /**      * And now for a little assembly.  Put together the menu items, progress      * bar and status text field.       */    Example1() {	super();	statusField.setFont(new Font("Dialog", Font.BOLD, 14));	startAction.setEnabled(true);	abortAction.setEnabled(false);	JMenuBar menuBar = new JMenuBar();	JMenu menu = new JMenu("Worker Thread Actions");	menu.add(startAction);	menu.add(abortAction);	menuBar.add(menu);	setLayout(new BorderLayout());	add(menuBar, BorderLayout.NORTH);	add(progressBar, BorderLayout.CENTER);	add(statusField, BorderLayout.SOUTH);    }}/**@begin Example2 Prompting the User from a Swing Worker Thread   This example is same as Example1 except that after the work methodhas run for about two seconds it blocks until the user has responded to a YES/NO/CANCEL modal dialog.  If the user doesn'tconfirm we short circuit the doWork() loop.  This demonstratesan idiom common to many worker threads: if the worker runs intoan unexpected condition it may need to bock until it hasalerted the user or collected more information from the userwith a modal dialog.  Doing so is a little complex because the dialog needs to be shown on the event dispatching thread, and theworker thread needs to be blocked until the user has dismissed the modal dialog.<p>We use <code>SwingUtilities.invokeAndWait()</code> to popup the dialog on the event dispatching thread.  Unlike <code>SwingUtilities.invokeLater()</code>, this method blocksuntil it's Runnable returns.   In this case the Runnable willnot return until the dialog has been dismissed.  We create an named inner Runnable class, <code>DoShowDialog</code>, to handle popping up the dialog.  There's a field, <code>DoShowDialog.proceeedConfirmed</code>, to record the usersreponse:<pre>class DoShowDialog implements Runnable {    boolean proceedConfirmed;    public void run() {	int n = JOptionPane.showConfirmDialog(Example2.this, "Proceed?");	proceedConfirmed = (n != JOptionPane.NO_OPTION);    }}</pre>Remember that because <code>JOptionPane.showConfirmDialog()</code> pops up a modal dialog, the call will block until the userhas dismissed the dialog by selecting one of yes,no,cancel.<p>To show the dialog and block the calling thread (that's the workerthread) until it's been dismissed, we just create an instance of <code>DoShowDialog</code> and call <code>SwingUtilities.invokeAndWait()</code>:<pre>DoShowDialog doShowDialog = new DoShowDialog();try {    SwingUtilities.invokeAndWait(doShowDialog);}catch (java.lang.reflect.InvocationTargetException e) {    e.printStackTrace();}</pre>We're catching the <code>InvocationTargetException</code>here because it should only happen if there's a bugin <code>DoShowDialog.run()</code>; and there shouldn't be.Once the <code>invokeAndWait()</code> call has returnedfrom executing on the event dispatching thread,we can return the users response, which is convenientlystored in <code>doShowDialog.proceedConfirmed</code>@end Example2*/class Example2 extends Example1{    /**     * Popup a modal confirm dialog and block until the user responds.     * Return true unless the user selects "NO".     */    boolean waitForUserConfirmation() throws InterruptedException {	/* We're going to show the modal dialog on the event dispatching	 * thread with SwingUtilities.invokeLater(), so we create a 	 * Runnable class that shows the dialog and stores the users	 * response.	 */	class DoShowDialog implements Runnable {	    boolean proceedConfirmed;	    public void run() {		int n = JOptionPane.showConfirmDialog(Example2.this, "Example2: Proceed?");		proceedConfirmed = (n != JOptionPane.NO_OPTION);	    }	}	DoShowDialog doShowDialog = new DoShowDialog();	/* The invokeAndWait utility can throw an InterruptedException,	 * which we don't bother with, and an InvocationException.	 * The latter occurs if our Runnable throws - which would indicate	 * a bug in DoShowDialog.  The invokeAndWait() call will not return 	 * until the user has dismissed the modal confirm dialog.	 */	try {	    SwingUtilities.invokeAndWait(doShowDialog);	}	catch (java.lang.reflect.InvocationTargetException e) {	    e.printStackTrace();	}	return doShowDialog.proceedConfirmed;    }    /**     * This is just a copy of Example1.doWork() with one extra wrinkle.     * After about two seconds we ask the user to confirm with     * a modal dialog (see waitForUserConfirmation()); if the answer     * is NO then we short circuit.     */    Object doWork() {	try {	    for(int i = 0; i < progressBar.getMaximum(); i++) {		updateStatus(i);		if (i == 4) {		    if (!waitForUserConfirmation()) {			updateStatus(0);			return "Not Confirmed";		    }		}		Thread.sleep(500);	    }	}	catch (InterruptedException e) {	    updateStatus(0);	    return "Interrupted";  // SwingWorker.get() returns this	}	return "All Done";         // or SwingWorker.get() returns this    }}public class ThreadsExample {    /**     * This is strictly boilerplate: set the look and feel, configure the     * frame, pack(), show().     */    public static void main(String[] args) {	String laf = UIManager.getCrossPlatformLookAndFeelClassName();	try {	    UIManager.setLookAndFeel(laf);	}	catch (Exception e) {	    e.printStackTrace();	    System.exit(1);	}	JFrame f = new JFrame("Threads Examples");	WindowListener l = new WindowAdapter() {	    public void windowClosing(WindowEvent e) {System.exit(0);}	};	f.addWindowListener(l); 	Container c = new ExampleContainer(new File("ThreadsExample.java"));	f.getContentPane().add(c);	f.pack();	f.show();    }}

⌨️ 快捷键说明

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