Vous êtes sur la page 1sur 4

7/8/2014 7.

3 Using invokeLater( ) and invokeAndWait( ) - Java Threads, Third Edition - - JAVA


http://book.javanb.com/java-threads-3rd/jthreads3-CHP-7-SECT-3.html 1/4

:
:>JavaThreads,ThirdEdition
7.3UsinginvokeLater()andinvokeAndWait()-JavaThreads,ThirdEdition
<DayDayUp>
7.3UsinginvokeLater()andinvokeAndWait()
IntheCharacterDisplayCanvasclass,wewereabletoworkaroundSwing'sthreadingrestrictionsbecauseallthecalls
thatmanipulatedSwingobjectscouldgointoaneventcallbackmethod(thepaintComponent()method).That'snotalways
convenient(orevenpossible).SoSwingprovidesanothermechanismthatallowsyoutoruncodeontheevent-dispatching
thread:theinvokeLater()andinvokeAndWait()methods.
WhichinvokeLater()?WhichinvokeAndWait()?
JavadefinestheinvokeLater()andinvokeAndWait()methodsintwodifferentclasses:
javax.swing.SwingUtilitiesandjava.awt.EventQueue.Thisisduetohistoricalreasons,andyou
canusewhicheverclassyoulike.Themethodsareidentical.TheinvokeLater()methodofthe
SwingUtilitiesclasssimplycallstheinvokeLater()methodoftheEventQueueclass,sotheyare
functionallyidentical;thesameistrueofthetwoinvokeAndWait()methods.
TheinvokeLater()andinvokeAndWait()methodsallowyoutodefineataskandasktheevent-processingthreadto
performthattask.Ifyouhaveanon-GUIthreadthatneedstoreadthevalueofaslider,forinstance,youputthecode
toreadthesliderintoaRunnableobjectandpassthatRunnableobjecttotheinvokeAndWait()method,which
returnsthevaluethethreadneedstoread.
Java Spring Certification
udemy.com/Java+Spring+Tutorial
Online Java Spring Tutorial, Taught By Experts. 50% Of f Normal Price.
Marine Deep Cycle Battery
genasun.com
Cycle 70% of your charge 3000 times with Genasun Lithium Marine Systems
7/8/2014 7.3 Using invokeLater( ) and invokeAndWait( ) - Java Threads, Third Edition - - JAVA
http://book.javanb.com/java-threads-3rd/jthreads3-CHP-7-SECT-3.html 2/4
Let'slookagainatourscorelabelclass.ThesetScore()methodofthatclasscanbecalledwhentheusertypesa
character(inwhichcaseitisrunningontheevent-dispatchingthread).Itcanalsobecalledwhentherandomcharacter
generatorsendsanewcharacter.Therefore,thesetScore()methodmustusetheinvokeLater()methodtomakethat
call:
package javathreads.examples.ch07.example1;
...
public class ScoreLabel extends JLabel implements CharacterListener {
...
private void setScore( ) {
SwingUtilities.invokeLater(new Runnable( ) {
public void run( ) {
setText(Integer.toString(score));
}
});
}
}
TheinvokeLater()methodtakesaRunnableobjectasitsparameter.Itsendsthatobjecttotheevent-dispatching
thread,whichexecutestherun()method.Thisiswhyit'salwayssafefortherun()methodtoexecuteSwingcode.
Notethattherun()methodisinitsownobject.Thisiswhywemadethescorevariablevolatileratherthanprotecting
itbyusingsynchronization.Synchronizingtherun()methodgrabsthelockoftheanonymousinnerclassobject,notthe
lockoftheScoreLabelobject.It'smucheasiertouseavolatilevariable.
Forthemostpart,theinvokeAndWait()methodlookssimilar,butithasthreeimportantsemanticdifferences.First,
theinvokeLater()methodrunsasynchronouslyatsometimeinthefuture.Youdon'tknowwhenitwillactuallyrun.On
theotherhand,theinvokeAndWait()methodissynchronous:itdoesnotreturnuntilitstargethascompleted
execution.Asaruleofthumb,then,youshouldusetheinvokeAndWait()methodtoreadthevalueofSwingcomponents
ortoensurethatsomethingisdisplayedonthescreenbeforeyoucontinueprogramexecution.Otherwise,youcanusethe
invokeLater()method.
TheseconddifferenceisthattheinvokeAndWait()methodcannotitselfbecalledfromtheevent-dispatchingthread.
ThethreadrunningtheinvokeAndWait()methodmustwaitfortheevent-dispatchingthreadtoexecutesomecode.No
thread,includingtheevent-dispatchingthread,canwaitforitselftodosomethingelse.Consequently,ifyouexecute
theinvokeAndWait()methodfromtheevent-dispatchingthread,itthrowsajava.lang.Error.Thatcausestheevent-
dispatchingthreadtoexit(unlessyou'vetakentheunusualstepofcatchingErrorobjectsinyourcode);inturn,your
entireprogrambecomesdisabled.
7/8/2014 7.3 Using invokeLater( ) and invokeAndWait( ) - Java Threads, Third Edition - - JAVA
http://book.javanb.com/java-threads-3rd/jthreads3-CHP-7-SECT-3.html 3/4
ThethirddifferenceisthattheinvokeAndWait()methodcanthrowanInterruptedExceptionifthethreadis
interruptedbeforetheevent-dispatchingthreadrunsthetarget,oranInvocationTargetExceptioniftheRunnable
objectthrowsaruntimeexceptionorerror.
Ifyouhavecodethatyouwanttotakeeffectimmediatelyandthatmightbecalledfromtheevent-dispatchingthread,
youcanusetheSwingUtilities.isEventDispatchThread()methodtocheckthethreadyourcodeisexecutingon.You
cantheneithercallinvokeAndWait()(ifyou'renotontheevent-dispatchingthread)orcalltheSwingmethods
directly.
WecouldusethatmethodinourScoreLabelclasslikethis:
package javathreads.examples.ch07.example2;
...
public class ScoreLabel extends JLabel implements CharacterListener {
...
private void setScore( ) {
if (SwingUtilities.isEventDispatchThread( ))
setText(Integer.toString(score));
else try {
SwingUtilities.invokeAndWait(new Runnable( ) {
public void run( ) {
setText(Integer.toString(score));
}
});
} catch (InterruptedException ie) {
} catch (InvocationTargetException ite) {}
}
}
7/8/2014 7.3 Using invokeLater( ) and invokeAndWait( ) - Java Threads, Third Edition - - JAVA
http://book.javanb.com/java-threads-3rd/jthreads3-CHP-7-SECT-3.html 4/4
<DayDayUp>
|Sitemap|||
Copyright2006-2007,Java,Allrightsreserved

Vous aimerez peut-être aussi