— Scott McNealy, Sun Microsystems Chairman, President and ceo


Make one instance of RyanAndMonicaJob



Download 40,57 Mb.
Pdf ko'rish
bet467/555
Sana26.05.2022
Hajmi40,57 Mb.
#609235
1   ...   463   464   465   466   467   468   469   470   ...   555
Bog'liq
Head First Java (Kathy Sierra, Bert Bates) (z-lib.org)

1
Make one instance of RyanAndMonicaJob. 
The RyanAndMonicaJob class is the Runnable (the job to do), 
and since both Monica and Ryan do the same thing (check 
balance and withdraw money), we need only one instance.
BankAccount
int balance
getBalance()
withdraw()
RyanAndMonicaJob
BankAccount account
run()
makeWithdrawal()
Runnable
2
Make two threads with the same Runnable 
(the RyanAndMonicaJob instance)
RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);
3
Name and start the threads 
one.setName(“Ryan”);
two.setName(“Monica”);
one.start();
two.start();
4
Watch both threads execute the run() method
(check the balance and make a withdrawal)
One thread represents Ryan, the other represents Monica. 
Both threads continually check the balance and then make a 
withdrawal, but only if it’s safe! 
In the run() method, do 
exactly what Ryan and 
Monica would do—check 
the balance and, if 
there’s enough money, 
make the withdrawal.
This should protect 
against overdrawing the 
account.
Except... Ryan and 
Monica always fall 
asleep after they 
check the balance but 
before they fi nish the 
withdrawal. 
if (account.getBalance() >= amount) {
try {
Thread.sleep(500);
} catch(InterruptedException ex) {ex.printStackTrace(); }
}
Ryan and Monica 
code


networking 
and
threads
you are here
4

Download 40,57 Mb.

Do'stlaringiz bilan baham:
1   ...   463   464   465   466   467   468   469   470   ...   555




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish