Download presentation
Presentation is loading. Please wait.
Published byOswald Golden Modified over 9 years ago
1
OPERATING SYSTEMS Frans Sanen
2
Recap of threads in Java Learn to think about synchronization problems in Java Solve synchronization problems in Java 2
3
One of the key success factors of Java Thread = flow of control Threads can share state If a program involves multiple threads, synchronization becomes an issue! Coordination is needed when several threads access and manipulate shared state 3
4
class Animation implements Runnable { Thread myThread; Animation (String name) { myThread = new Thread( this ); myThread.start(); } public void run() { while ( true ) { // Draw Frames... repaint(); }
5
class Animation extends Thread { public void run() { while (true ) { // Draw Frames... repaint(); }
6
Wait and notify monitor as the underlying mechanism Thread can suspend itself by calling wait() Waiting thread will be suspended if another thread executes notify() Java also provides notifyAll() method Methods wait(), notify() and notifyAll() only can be invoked from within monitor regions
7
Monitor guarantees mutual exclusion when an object is executing in a monitor region Synchronized method public void synchronized doSth() {...} Synchronized code block synchronized (this) {...}
9
9
10
Producer produces items and puts them in a shared buffer Consumer consumes items and gets them out a shared buffer Producer can’t produce items if the buffer is full. Consumer can’t consume items if the buffer is empty. 10
11
Readers try to read (access) shared data Writers try to write (manipulate) shared data Only one writer can write shared data at a given moment in time (“no two writers”). It never may be the case that both a reader and a writer are working with shared data simultaneously (“no reader and writer at the same time”). 11
12
Good luck!
13
If two or more threads modify a shared object, declare the methods / code blocks that carry out the modification as synchronized. If a thread must wait for the state of a shared object to change, it should wait inside the object, not outside, by entering the synchronized method / code block and calling wait(). Whenever a method / code block changes the state of a shared object, it should call notify() to give waiting threads a chance to see if circumstances have changed. Keep the synchronized granularity as low as possible to maximize parallelism.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.