Java Reference
In-Depth Information
thd.setDefaultUncaughtExceptionHandler(uceh); , you will see List-
ing 4-20 ' s output.
Caution Thread declaresseveraldeprecatedmethods,including stop() (stopan
executing thread). These methods have been deprecated because they are unsafe. Do
not usethesedeprecatedmethods.(Iwillshowyouhowtosafelystopathreadlaterin
thischapter.)Also,youshouldavoidthe static void yield() method,whichis
intendedtoswitchexecutionfromthecurrentthreadtoanotherthread,becauseitcan
affectportabilityandhurtapplicationperformance.Although yield() mightswitch
to another thread on some platforms (which can improve performance), yield()
might only return to the current thread on other platforms (which hurts performance
because the yield() call has only wasted time).
Thread Synchronization
Throughoutitsexecution,eachthreadisisolatedfromotherthreadsbecauseithasbeen
given its own method-call stack. However, threads can still interfere with each other
whentheyaccessandmanipulateshareddata.Thisinterferencecancorrupttheshared
data, and this corruption can cause an application to fail.
Forexample,consideracheckingaccountinwhichahusbandandwifehavejointac-
cess.Supposethatthehusbandandwifedecidetoemptythisaccountatthesametime
withoutknowingthattheotherisdoingthesamething. Listing4-22 demonstratesthis
scenario.
Listing 4-22. A problematic checking account
class CheckingAccount
{
private int balance;
CheckingAccount(int initialBalance)
{
balance = initialBalance;
}
boolean withdraw(int amount)
{
if (amount <= balance)
{
try
Search WWH ::




Custom Search