Lecture 10

homeContentsIndexPrevNext

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 CANNOT
 
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


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. 
 

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