Lecture
10





Lecture Topic:
Threads, Synchronization and
Atomic Operations
- Threads
- Enable parallelism within the
program
Threads simply extend that concept from
switching between several different programs, to switching between
several different functions executing simultaneously within a single
program.
Core Java
- public class <class_name> extends Applet implements
runnable {
Thread t_name;
public void start ( ){---------------}
public void stop ( ){---------------}
public void run ( ){-----------------}
- }
- Example
- public class Digital Threads extends Applet implements
runnable
{
- Thread runner;
Graphic g;
Frame f;
public void start( ) {
if ( runner == null ) {
runner = new Thread(this);
runner.start( );
}
- }
- public void stop ( ){
if ( runner != null ) {
runner == null;
runner.stop( );
}
- }
-
- Synchronization
Synchronized methods
be Interrupt by other Threads
- Synchronized methods prevent other
Threads
-
- Example
synchronized private void draw ( ) {
Dimension dim = f.size ( );
int height = dim.height - 60;
int width = dim.width;
Date theDate = new Date( );
g.clearRect( 10, height, 150, 15 );
g.drawString( theDate, toString( ),
10, height + 10 );
}
public void run ( ){
while ( true ) {
draw ( );
try { Thread, sleep(1000); }
catch ( Interrupted exception e) { }
}
-
- Atomic Operations
- Synchronized methods are atomic!
- appear to happen all at once
- Synchronized methods cannot be
interrupted by other threads.
- Synchronized methods prevent other
threads from running.
- A pulldown menu can run on a
synchronized method which stops your method from running.
- If your task takes longer than your
sleep time, it may not be updated frequenctly enough
- Synchronized methods allow only one
thread to access data at a time. This can prevent data corruption.
It prevents rave conditions. Just like logic hazards.
- No two synchronized methods may run at
the same time!
Homework(source code, click me!)
Implement a java application that has 3 random
threads, each of which sleep between 50~1000ms. Use System.out.println(
runner1,++++); print out the numbers of + sign, i.e.,
runner1 ++
runner2 +++
runner4 +++++
runner3 ++++. Runs until winner reaches 10.




Last Update: 2/6/97
Copyright © 1996,1997 - Douglas Lyon
Lyon@cse.bridgeport.edu