SDSU CS 580 Client-Server
Spring Semester, 2004
Threads part 1
Previous    Lecture Notes Index    Next    
© 2004, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 24-Feb-04


References


The Java Programming Language , 2 nd Ed. Arnold & Gosling, Addison-Wesley, 1998

The Java Language Specification , Gosling, Joy, Steele, Addison-Wesley, 1996, Chapter 17 Threads and Locks.

Java 1.4.1 on-line documentation http://java.sun.com/products/jdk/1.2/docs/index.html

VisualWorks Application Developers Guide, Cincom, Chapter 11 (Smalltalk), see docs/AppDevGuide.pdf in the VW installation



Doc 16, Threads part 1 Slide # 2
Reading

Java Network Programming, 2nd Ed., Harold, Chapter 5. (Java)

VisualWorks Application Developers Guide, Cincom, Chapter 11 (Smalltalk), see docs/AppDevGuide.pdf in the VW installation

Source Code

Smalltalk
See rugby.sdsu.edu_cs580 Store repository
Package ThreadLecture1



Doc 16, Threads part 1 Slide # 3

Concurrent Programming




Safety

Liveness

Nondeterminism

Communication


Doc 16, Threads part 1 Slide # 4

Threads - Light Weight Processes





Difference from Processes (fork())

Processes (Heavy Weight)

Thread (Light Weight Process)



Doc 16, Threads part 1 Slide # 5

Creating Threads

Smalltalk

fork


   | out |
   out := WriteStream on: String new.
   out
      nextPutAll: 'Create the thread';
      cr.
   
   [1 to: 4
      do: 
         [:each | 
         out
            nextPutAll: 'Message ' , each printString;
            cr]] 
         fork.
   out
      nextPutAll: 'Thread started. The End';
      cr.
   Transcript
      clear;
      show: out contents
Output

Create the thread
Thread started. The End
1234


Doc 16, Threads part 1 Slide # 6
newProcess

| hello |
hello := [Transcript show: 'Hi';cr] newProcess.
   
“hello will not run unit it is activated via resume”
   
hello resume.

Both fork and newProcess return an instance of Process

With Arguments

   | printer printProcess |
   printer := 
         [:a :b :c | 
         Transcript
            print: a + b + c;
            cr;
            flush].
   printProcess := printer newProcessWithArguments: #(1 2 3).
   printProcess resume


Doc 16, Threads part 1 Slide # 7
Creating ThreadsJava


class  ExtendingThreadExample  extends Thread {
   public void run() {
      for  ( int  count = 0;  count < 4; count++)
         System.out.println( "Message " + count +
                          " From: Mom" );
   }
    
   public static void main( String[]  args ) {
      ExtendingThreadExample  parallel  = 
         new ExtendingThreadExample();
      System.out.println( "Create the thread");
      parallel.start();
      System.out.println( "Started the thread" );
      System.out.println( "End" );
   }
}
Output
Create the thread
Message 0 From: Mom
Message 1 From: Mom
Message 2 From: Mom
Message 3 From: Mom
Started the thread
End

Doc 16, Threads part 1 Slide # 8
Second Method for Creating a Thread


class  SecondMethod  implements  Runnable {
   public  void  run() {
      for  ( int  count = 0;  count < 4; count++)
         System.out.println( "Message " + count +  " From: Dad");
   }
   
   public static void main( String[]  args ) {
      SecondMethod  notAThread  = new SecondMethod();
      Thread  parallel  =  new Thread( notAThread );
   
      System.out.println( "Create the thread");
      parallel.start();
      System.out.println( "Started the thread" );
      System.out.println( "End" );
   }
}
Output
Create the thread
Message 0 From: Dad
Message 1 From: Dad
Message 2 From: Dad
Message 3 From: Dad
Started the thread
End

Doc 16, Threads part 1 Slide # 9
Giving a Thread a Name


public class  WithNames  implements  Runnable {
   public  void  run() {
      for  ( int  count = 0;  count < 2; count++)
         System.out.println( "Message " + count +  " From: " + 
                        Thread.currentThread().getName() );
   }
   
   public static void main( String[]  args ) {
      Thread  a  =  new Thread(new WithNames(), "Mom" );
      Thread  b  =  new Thread(new WithNames(), "Dad" );
   
      System.out.println( "Create the thread");
      a.start();
      b.start();
      System.out.println( "End" );
   }
}
Output
Create the thread
Message 0 From: Mom
Message 1 From: Mom
Message 0 From: Dad
Message 1 From: Dad
End


Doc 16, Threads part 1 Slide # 10
SimpleThread for Use in Future Examples



public class  SimpleThread  extends Thread
   {
   private  int  maxCount =  32;
   
   public  SimpleThread(  String  name )
      {
      super( name );
      }
   
   public  SimpleThread(  String  name, int repetitions )
      {
      super( name );
      maxCount  =  repetitions;
      }
   
   public  SimpleThread(  int repetitions )
      {
      maxCount  =  repetitions;
      }
   
   public  void run()
      {
      for  ( int  count = 0;  count < maxCount; count++)
         {
         System.out.println( count + " From: " + getName() );
         }
      }
   }

Doc 16, Threads part 1 Slide # 11
Show Some Parallelism


public class  RunSimpleThread
   {
   public static void main( String[]  args )
      {
      SimpleThread  first      = new SimpleThread( 5 );
      SimpleThread  second  = new SimpleThread( 5 );
      first.start();
      second.start();
      System.out.println( "End" );
      }
   }
Output- On Rohan
End
0 From: Thread-0
1 From: Thread-0
2 From: Thread-0
0 From: Thread-1
1 From: Thread-1
2 From: Thread-1
3 From: Thread-0
3 From: Thread-1
4 From: Thread-0
4 From: Thread-1

Doc 16, Threads part 1 Slide # 12

Multiple Processors

Java

Java on a Solaris machine with multiple processors can run threads on different processors
If you run the last example on a single processor machine the results may be completely different.
Smalltalk

VisualWorks claims to have some native thread support

I have not used this feature

Doc 16, Threads part 1 Slide # 13
Showing Parallelism – Smalltalk

   | out |
   out := WriteStream on: String new.
   
   [10 timesRepeat: [out nextPutAll: 'A ']] fork.
   [10 timesRepeat: [out nextPutAll: 'B ']] fork.
   
   (Delay forMilliseconds: 20) wait.
   Transcript
      clear;
      show: out contents
   
Output

A A A A A A A A A A B B B B B B B B B B
What is going on?

Doc 16, Threads part 1 Slide # 14

Thread Scheduling





Doc 16, Threads part 1 Slide # 15

Priorities


Each thread has a priority

If there are two or more active threads


Java Priorities
java.lang.Thread field
Value
Thread.MAX_PRIORITY
10
Thread.NORM_PRIORITY
5
Thread.MIN_PRIORITY
1

Smalltalk Priorities
Priority
ProcessScheduler
Methods
Purpose
100
timingPriority
Processes that are dependent on real time
98
highIOPriority
Critical I/O processes, such as network input handling
90
lowIOPriority
Normal input/output activity, such as keyboard input
70
userInterruptPriority
High-priority user interaction; such a process pre-empts window management, so it should be of limited duration
50
userSchedulingPriority
Normal user interaction
30
userBackgroundPriority
Background user processes
10
systemBackgroundPriority
Background system processes
1
systemRockBottomPriority
The lowest possible priority


Doc 16, Threads part 1 Slide # 16
Setting Priorities

Continuously running parts of the program should have lower-priority than rare events

User input should have very high priority

A thread that continually updates some data is often set to run at MIN_PRIORITY


Doc 16, Threads part 1 Slide # 17
Java Examples

public class  PriorityExample
   {
   public static void main( String[]  args )
      {
      SimpleThread  first      = new SimpleThread( 5 );
      SimpleThread  second  = new SimpleThread( 5 );
      second.setPriority( 8 );
      first.start();
      second.start();
      System.out.println( "End" );
      }
   }
Output
On Single ProcessorOn Multiple Processor Rohan
0 From: Thread-5End
1 From: Thread-50 From: Thread-3
2 From: Thread-51 From: Thread-3
3 From: Thread-52 From: Thread-3
4 From: Thread-50 From: Thread-2
0 From: Thread-43 From: Thread-3
1 From: Thread-41 From: Thread-2
2 From: Thread-42 From: Thread-2
3 From: Thread-44 From: Thread-3
4 From: Thread-43 From: Thread-2
End4 From: Thread-2


Doc 16, Threads part 1 Slide # 18
Smalltalk Priority Example

   | out |
   out := WriteStream on: String new.
   
   [10 timesRepeat: [out nextPutAll: 'A ']] 
      forkAt: Processor userSchedulingPriority.
   
   [10 timesRepeat: [out nextPutAll: 'B ']] 
      forkAt: Processor userSchedulingPriority + 1.
   
   (Delay forMilliseconds: 100) wait.
   Transcript
      clear;
      show: out contents


Output

B B B B B B B B B B A A A A A A A A A A


Doc 16, Threads part 1 Slide # 19
Threads Run Once

When a Java or Smalltalk thread ends it cannot be restarted

public class RunOnceExample extends Thread {
   public void run() {
      System.out.println(  "I ran" );
   }
   
   public static void main( String args[] ) throws Exception {
      RunOnceExample onceOnly = new RunOnceExample();
      onceOnly.setPriority( 6 );
      onceOnly.start();
   
      System.out.println( "Try restart");
      onceOnly.start();
   
      System.out.println( "The End");
   }
}
Output
I ran
Try restart
The End


Doc 16, Threads part 1 Slide # 20
Thread Scheduling

Time-slicing


Time-slicing

Non time-sliced threads run until:

Java

Does not specify if threads are time-sliced or not

Implementations are free to decide

VisualWorks

Threads are not time-sliced

Doc 16, Threads part 1 Slide # 21
Testing for Time-slicing & Parallelism

public class  InfinityThread  extends Thread
   {
   public  void run()
      {
      while ( true )
         System.out.println(  "From: " + getName() );
      }
   
   public static void main( String[]  args )
      {
      InfinityThread  first      = new InfinityThread( );
      InfinityThread  second  = new InfinityThread( );
      first.start();
      second.start();
      }
   }
Output if Time-sliced

A group of "From: Thread-a" will be followed by a group of "From: Thread-b" etc.

Output if not Time-sliced, Single Processor

"From: Thread-a" will repeat "forever"

Multiple Processor
"From: Thread-a" and "From: Thread-b" will intermix "forever"

Doc 16, Threads part 1 Slide # 22

Java Types of Threads: user and daemon




Daemon thread

User thread




The Java Virtual Machine continues to execute the program until either of the following occurs:




Doc 16, Threads part 1 Slide # 23
Daemon example



public class DaemonExample extends Thread
   {
   public  static  void  main( String  args[] )
      {
      DaemonExample  shortLived      = new DaemonExample( );
      shortLived.setDaemon( true );
      shortLived.start();
      System.out.println( "Bye");
      }
   
   public  void run()
      {
      while (true)
         {
         System.out.println(  "From: " + getName()  );
         System.out.flush();
         }
      }
   }
Output
From: Thread-0 (Repeated many times)
Bye
From: Thread-0 (Repeated some more, then the program ends)

Doc 16, Threads part 1 Slide # 24

Thread Control

Thread States


  • Only one thread per processor can be running at a time
  • A thread is ready to run but is not currently running
  • A thread that is suspended or waiting for a resource

Doc 16, Threads part 1 Slide # 25

Yield


Allow another thread of the same priority to run

public class  YieldThread  extends Thread {
   public  void run() {
      for  ( int  count = 0;  count < 4; count++) {
         System.out.println( count + " From: " + getName() );
         yield();
      }
   }
   
   public static void main( String[]  args )  {
   
      YieldThread  first      = new YieldThread();
      YieldThread  second  = new YieldThread();
        first.setPriority( 1);
        second.setPriority( 1);
      first.start();
      second.start();
      System.out.println( "End" );
   }
}
Output (Explain this)
0 From: Thread-0
0 From: Thread-1
1 From: Thread-0
1 From: Thread-1
2 From: Thread-0
2 From: Thread-1
3 From: Thread-0
End
3 From: Thread-1

Doc 16, Threads part 1 Slide # 26
Smalltalk Yield Example

   | out |
   out := WriteStream on: String new.
      
   [10 timesRepeat: 
         [out nextPutAll: 'A '.
         Processor activeProcess yield]] 
         fork.
      
   [10 timesRepeat: 
         [out nextPutAll: 'B '.
         Processor activeProcess yield]] 
         fork.
   
   (Delay forMilliseconds: 100) wait.
   Transcript
      clear;
      show: out contents

Output

A B A B A B A B A B A B A B A B A B A B


Doc 16, Threads part 1 Slide # 27

Suspend & Resume

Smalltalk

suspend

suspendUnconditionally
resume

   | out a |
   out := WriteStream on: String new.
   
   a :=     [3 timesRepeat: 
               [out nextPutAll: 'A '.
               Processor activeProcess yield]] 
               fork.
   
   [a suspend.
   4 timesRepeat: 
         [out nextPutAll: 'B '.
         Processor activeProcess yield].
   a resume] 
         fork.
   
   (Delay forMilliseconds: 100) wait.
   Transcript
      clear;
      show: out contents
Output
A B B B B A A


Doc 16, Threads part 1 Slide # 28
Suspend & Resume – Java

The following Thread methods are not thread safe


These methods can leave your Java program in unstable states

You should not use them


Doc 16, Threads part 1 Slide # 29

Killing a Thread

Smalltalk

terminate


Example
   | bill |
   Transcript clear.
   bill :=  [3 timesRepeat: 
            [Transcript
               show: 'A ';
               cr]] forkAt: Processor userSchedulingPriority - 5.
   
   bill terminate.
   Transcript show: 'Killed bill'.

Output
Killed bill


Doc 16, Threads part 1 Slide # 30
Killing a Thread - Java

stop


destroy

There is no good way to really kill a Java thread

Later lectures will cover some suggestions for doing this



Copyright ©, All rights reserved.
2004 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
OpenContent license defines the copyright on this document.

Previous    visitors since 24-Feb-04    Next