

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
These are the Lecture Slides of Java Programming Language which includes Applet Class, Passing Parameters to Applets, Conversions, Applications and Applets, Running a Program, Applet, Application, Mouse Event, Keyboard Event etc. Key important points are: Multithreading, Threads Concept, Creating Threads, Extending, Implementing, Runnable Interface, Controlling Threads, Thread Status, Thread Groups, Synchronization
Typology: Slides
1 / 25
This page cannot be seen from the preview
Don't miss anything!
Multiple threads on multiple CPUs
Multiple threads sharing a single CPU
Thread 3
Thread 2
Thread 1
Thread 3
Thread 2
Thread 1
TestThread
Run Click the Run button to access the DOS prompt; then type java TestThread
TestRunnable
Run Click the Run button to access the DOS prompt;then type java TestRunnable Docsity.com
Thread created
new
ready
running
finished
blocked
start
run
yield, or time expired
stop or complete stop
suspend, sleep, or wait
stop
resume, notify, or notifyAll
A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account causes conflict.
Step balance thread[i] thread[j] 1 0 newBalance =^ bank.getBalance() + 1; 2 0 newBalance =^ bank.getBalance() + 1; 3 1 bank.setBalance(newBalance); 4 1 bank.setBalance(newBalance);
PiggyBankWithoutSync Run
PiggyBank -balance +getBalance+setBalance
1
100
PiggyBankWithoutSync -PiggyBank bank-Thread[] thread +main
Object
Object
AddAPennyThread
+run()
Thread
1
1
To avoid resource conflicts, Java uses the keyword synchronized to synchronize method invocation so that only one thread can be in a method at a time. To correct the data-corruption problem in Example 13.3, you can rewrite the program as follows:
PiggyBankWithSync Run
public void start() { while (true) { stillClock.repaint(); try { Thread.sleep(1000); } catch(InterruptedException ex) { } } }
What is wrong in this code? As long as the while loop is running, the browser cannot serve any other event that might be occurring.
public class MyApplet extends JApplet implements Runnable { private Thread timer = null; public void init() { timer = new Thread(this); timer.start(); } ... public void run() { ... } }