14.Threads

Document Sample
14.Threads Powered By Docstoc
					             ISYE 7210--Simulation of Real-Time Systems
                                   Fall 2005


                  Interfaces, Runnable, Threads, Lists
                              7210 Class Web site:
                         www.chmsr.gatech.edu/ISyE7210/

                   Horstmann & Cornel (7th ed) Download Web site:
                         www.horstmann.com/corejava.html



                           Christine M. Mitchell

             Center for Human-Machine Systems Research (chmsr)
                 School of Industrial and Systems Engineering
               (chmsr lab) ISyE Main, Room 426, 404 385-0363
              (office) ISyE Groseclose, Room 334, 404 894-4321

                           {cm}@chmsr.gatech.edu

(10.19.05)
                                                                    CHMSR
                                                                        1
                                      Timing in Java

            Java lang Thread.sleep(….)

            Java.lang class Thread

            Java.lang interface Runnable

            java.lang class Object

            Synchronization

            Event dispatch thread (in Package javax.swing)




(10.19.05)                                                    2
                             Timing in Java: “Selfish” Thread

            A program consisting of one thread can sleep

            Thread API (partial)

             public static void sleep(long millis) throws Interrupted Exception
              Causes currently executing thread to sleep (temporarily cease
                 execution) for the specified number of milliseconds
              Thread does not lose ownership of any monitors


            public static void sleep(…)
              static means that sleep(…) is a method of Class, Thread
              sleep(…) is not an instance method of Thread


                 Thread.sleep(2000); //OK—sleep(…) used as class method

                 Thread aThread = new Thread( );
                 aThread.sleep(2000); //ERROR—sleep(…) is not an instance method

(10.19.05)                                                                         3
                         Bounce Program: Uses a “Selfish” Thread
            Bounce
              Animates a bouncing ball

            Begin Bounce
              Create a JFrame by calling
                 BounceFrame constructor

            BounceFrame constructor
              Creates a JPanel with a button, “Start”
              When user clicks “Start”, ActionListener
                calls addBall( )
              addBall( ) {…Thread.sleep(5) ;….}
              Thread has complete control for
                specified milliseconds

            This program consists of exactly one thread

            Thread.sleep does not create a new thread



(10.19.05)                                                         4
                              Bounce Program: Uses a “Selfish” Thread
   public class Bounce
   {
     public static void main(String[] args)
     {….} }//end Bounce class

   public class BounceFrame extends JFrame
   {
     public BounceFrame( )
     {
        addButton( buttonPanel, "Start", new ActionListener()
         {
            public void actionPerformed (ActionEventevent)
            { addBall(); } } //end addButton(…..)

      public void addBall()
      {
        try{ Ball ball = new Ball();
             panel.add(ball);
            for (int i = 1; i <= 1000; i++)
            { ball.move(panel.getBounds());
               panel.paint(panel.getGraphics());
               Thread.sleep(DELAY);
          }} //end addBall( )
(10.19.05)                                                              5
                                              Thread Class API
            Java.lang class Thread
              public class Thread extends Object implements Runnable
               Constructors
                    Thread( )
                          Allocates a new Thread object


                     Thread(String aName)
                        Allocates a new Thread object with name, aName


               Method required of any instance or subclass of Thread that implements Runnable
                interface
                       void run( )
               Any instance or subclass of Thread must define a body for run( )


                                void run( )
                                {..
                                   //body
                                  ….
                                }


(10.19.05)                                                                                       6
                                             Thread Class API

            Java.lang class Thread
         public class Thread extends Object implements Runnable
       Methods (most useful)
          static Thread currentThread( )
               Returns a reference to the currently executing thread object
                       Thread.currentThread( )

                 String getName( )
                   Returns this thread's name
                        Thread aThread = new Thread(“Simulation Interface”)
                        aThread.getName( ) returns String, Simulation Interface


               void run( )
                        If this thread was constructed using a separate Runnable run object,
                             then that Runnable object's run method is called
                             otherwise, this method does nothing and returns




(10.19.05)                                                                                     7
                                            Thread Class API
            Java.lang class Thread
            Methods (most useful)
               void setName(String name)
                      Changes thread name to the argument name
                        Thread aThread = new Thread( );
                        aThread.setName(“Simulation”);


               static void sleep(long millis)
                      Causes currently executing thread to cease execution for specified
                       number of milliseconds
                             Thread.sleep(aLongNumber);


               void start (long millis)
                      Causes this thread to begin execution; JVM calls run( ) of this thread
                       instance

               void start (long millis)
                      Causes this thread to begin execution; JVM calls run( ) of this thread instance
                            Thread aThread = new Thread(“example”); //create a thread
(10.19.05)
                            aThread.start( ); //start running                                            8
                                    Implementing a Thread

            Method(1): selfish thread (Bounce example)
                       Thread.sleep(long millis)
            Method (2): Declare a class that instantiates or subclasses Thread and overrides
             Thread’s run( )
                       aClass extends Thread
                       {
                             …
                             run( )
                             {
                               …
                             } //end run( )
                              …
                       }
            Method (3) Create a class that implements Runnable
                       public class aNewClass implements Runnable
                       {
                           ….
                           Thread aThead = new Thread(“Example of Runnable”);
                           aThread.start( );
                           ….. }}} //end NewClass definition
(10.19.05)                                                                                      9
       Threads that Share (Method(2)): Subclass Thread & Implement Runnable

                              NewThread extends Thread {….}
                              NewThread aThread = new NewThread( );
                              aThread.start( );

            Implementation never calls run( ) directly
                                                               //BallThread extends Thread
                Thread’s start ( ) indirectly calls run ( )   {
                                                                      private Ball b
        //public class BounceFrame extends JFrame {              ….
                                                                 public void run()
                 public void addBall()
                                                                  {
             {
                                                                     try
               Ball b = new Ball();
                                                                     {for (int i = 1; i <= 1000; i++)
               ….
                                                                       {
               BallThread thread = new BallThread(b);
                                                                          b.move( );
               thread.start( );
                                                                          sleep(5);
           } //end addBall
                                                                       }}
          …
                                                                     catch (InterruptedException e) { }
        } / end BounceFrame
                                                                   } //end run( )
                                                                      …..
                                                                }


(10.19.05)                                                                                                10
       Threads that Share (Method(2)): Subclass Thread & Implement Runnable

            Save a class in Bounce example
               Rewrite Ball & eliminate BounceThread

            Ball extends Thread, therefore, Ball must implement Runnable

                           class Ball extends Thread
                                public void run( )
                                {
                                   public void run()
                                   {
                                     try
                                     {for (int i = 1; i <= STEPS; i++)
                                     {
                                       x += dx;
                                       y += dy;
                                       …….
                                       sleep(5)
                                       }
                                      catch (InterruptedException e) { }
                               } //end run( ) …….
                           }

(10.19.05)                                                                    11
    Threads that Share (Method(2)): Subclass Thread & Implement Runnable

   public class SimpleThread extends Thread            //tester class for SimpleThread
   {
     public SimpleThread(String str)                   public class TwoThreadsTest
     {                                                 {
        super(str);                                      public static void main(String[ ] args)
      }                                                  {
      public void run()                                     new SimpleThread(“Jamaica”). start( );
      {                                                    new SimpleThread(“Fiji”). start( );
        for (int i = 0; i < 10; i++)                      }}
        {
            System.out.println(i + " " + getName());
                                                       Output                     5 Jamaica
            try                                        0 Jamaica                  5 Fiji
            {                                          0 Fiji                     6 Jamaica
               sleep((long)(Math.random() * 1000));    1 Jamaica                  6 Fiji
             }                                         1 Fiji                     7 Jamaica
             catch (InterruptedException e) {}         2 Jamaica                  7 Fiji
             }
                                                       2 Fiji                     8 Jamaica
          System.out.println("DONE! " + getName());
          }
                                                       3 Jamaica                  8 Fiji
   }                                                   3 Fiji                     9 Jamaica
                                                       4 Jamaica                  9 Fiji
                                                       4 Fiji                     DONE! Jamaica
                                                                                  DONE! Fiji
(10.19.05)                                                                                           12
                                     Runnable Interface API

            java.lang interface Runnable
                void run( )


            public interface Runnable
               public void run()
                    Use when an object will be run by an instance of Thread
                    Classes that implement Runnable must define run( )


            Objects implementing interface Runnable
               Create a thread
               Start the thread by calling start( )
               start( ) causes object's run( ) to execute (Java Virtual Machine)
               run( ) can be called in a separately executing thread


            Runnable allows a class to be active while not subclassing Thread



(10.19.05)                                                                          13
      Threads that Share (Method (3)): Create a Class that Implements Runnable

      If the class already subclasses       But need a thread start( ) method
       another class, must
         implement Runnable interface

                                           class Animation extends JApplet
    class Animation extends JApplet             implements Runnable
         implements Runnable               {
       public void run( )                     private Thread runner;
       {                                      public void start( )
          …….                                 {
         public void run()                       runner = new Thread(this);
          {                                      runner.start( );
         ……                                     }
         } //end run( )                         ……
      …….                                  }
    }




(10.19.05)                                                                        14
    Threads that Share (Method (3)): Create a Class that Implements Runnable

   /**                                                 class PrintNumbers implements Runnable
     TestRunnable.java                                 {
     @author cm                                            long upperBound = 0;
     Created on October 2, 2005, 7:26 PM                   PrintNumbers(long upperBd)
     */                                                    { this.upperBound = upperBd; }
   public class TestRunnable                               public void run()
   {                                                       {
       /**                                                    System.out.println("Iterations: 0 to " +
                                                               this.upperBound);
         Tests PrintNumbers class
                                                              for(int i=0; i <= this.upperBound; i++)
        */
                                                              {
   public static void main(String [] Args)
                                                                  System.out.println("i = "+ i);
        {
                                                                  try
           long upper = 100;
                                                                  {
           PrintNumbers p = new PrintNumbers(upper);
                                                                     wait(1);
           Thread p = new Thread( )
                                                                  }
            p.start();
                                                                  catch (InterruptedException exception)
       }
                                                                  {
   } //end classTestRunnable
                                                                      System.out.println("Exception in catch
                                                                       for PrintNumbers");}
                                                                  } //end run(
                                                       } //end class PrintNumbers

(10.19.05)                                                                                                     15
                                 Timing in Java: Object class

        java.lang Class Object
                          public class Object

            Object methods
              void wait ( )
                  Causes current thread to wait until another thread invokes the
                     notify( ) method or the notifyAll( ) method for this object

                void wait (long timeout)
                  Causes current thread to wait until either another thread invokes
                     the notify( ) method or the notifyAll( ) method for this object, or a
                     specified amount of time has elapsed.

                void notify( )
                  Wakes up a single thread that is waiting on this object's monitor


                void notifyAll( )
                  Wakes up all threads that are waiting on this object's monitor



(10.19.05)                                                                                   16
                                           Synchronizing Threads
            Object
               wait( )
                   waits indefinitely for notification


               wait(long timeout)
                    waits   until the timeout period has elapsed

               wait( ) for notification


            Object wait methods can
               Synchronize threads


               Replace sleep( )
                    Easily   wake wait( ) with a notify( ) or notifyAll( )

               Note: sleeping thread cannot be awakened prematurely



(10.19.05)                                                                    17
                    Synchronizing Threads: Producer/Consumer Scenario
            Scenario
               Producer generates a stream of data
                  One thread (the producer) writes data to a file


               Consumer consumes the data
                   Another   thread (the consumer) reads data from the same file

            Concurrent threads share the same resource, the file

            Producer & consumer share data through a common CubbyHole object
               Ideally, Consumer gets each data value exactly once
               But, no one checks


            Sychronization ensures, with put( ) & get( ) of CubbyHole, that consumer gets a
             data value exactly once!
               Both threads should be synchronized
               Use Object’s wait( ) & notifyAll( )


(10.19.05)                                                                                     18
                    Synchronizing Threads: Producer/Consumer Scenario
   public class Producer extends Thread             public class Consumer extends Thread
   {                                                {
     private CubbyHole cubbyHole;                     private CubbyHole cubbyHole;
     private int number;                              private int number;

                                                      public Consumer(CubbyHole c, int number)
      public Producer(CubbyHole c, int number)        {
      {                                                  cubbyhole = c;
         cubbyhole = c;                                  this.number = number;
         this.number = number;                         }
       }
                                                    public void run()
      public void run()
                                                      {
      {
                                                        int value = 0;
        for (int i = 0; i < 10; i++)
        {                                                for (int i = 0; i < 10; i++)
           cubbyhole.put (number, i);                    {
           try                                              value = cubbyHole.get(number)
           {                                             }
               sleep((int)(Math.random() * 100));       }
           }                                        } //end Consumer
           catch (InterruptedException e) { }
           } } } //end Producer

(10.19.05)                                                                                       19
                Synchronizing Threads: Producer/Consumer Scenario
   public class CubbyHole                           //CubbyHole
   {
     private int contents;                          public synchronized void put(int who, int value)
     private boolean available = false;             {
                                                      while (available == true)
     public synchronized int get(int who)
                                                      {
     {                                                    try
       while (available == false)                         {
       {                                                     wait();
         try                                               }
                                                         catch (InterruptedException e) { }
         {
                                                       }
            wait();                                       contents = value;
         }                                                available = true;
         catch (InterruptedException e) { }               System.out.println("Producer " + who + "
       }                                                        put: " + contents);
                                                          notifyAll();
           available = false;
                                                      } //end put
           System.out.println("Consumer " + who +
         " got: " + contents);                      } //end CubbyHole
           notifyAll();
           return contents;
       }//end get( )

(10.19.05)                                                                                             20
                Synchronizing Threads: Producer/Consumer Scenario
   // ProducerConsumerTest                     // ProducerConsumerTest
   public class ProducerConsumerTest           Producer 1 put: 3
   {                                           Consumer 1 got: 3
      public static void main(String[] args)
                                               Producer 1 put: 4
      {
                                               Consumer 1 got: 4
         CubbyHole c = new CubbyHole();
                                               Producer 1 put: 5
         Producer p1 = new Producer(c, 1);
         Consumer c1 = new Consumer(c,         Consumer 1 got: 5
        1);                                    Producer 1 put: 6
         p1.start();                           Consumer 1 got: 6
         c1.start();                           Producer 1 put: 7
      }
                                               Consumer 1 got: 7
   }
                                               Producer 1 put: 8
   Output
   Producer 1 put: 0
                                               Consumer 1 got: 8
   Consumer 1 got: 0                           Producer 1 put: 9
   Producer 1 put: 1                           Consumer 1 got: 9
   Consumer 1 got: 1
   Producer 1 put: 2
   Consumer 1 got: 2

(10.19.05)                                                               21
                             How Sims will Use Threads & ‘Sleep:

            Sim0, Sim1
                 public void simulate()
                 Thread.sleep( (long) (delay ));

            Sim2, Sim3 & 4
                 public synchronized void simulate()
                 …..
                 …..
                 …..
                 try
                   {
                     wait(); // wait until 'notify()ed'
                   }
                   catch(InterruptedException ie)
                   {
                     continue;
                   }
(10.19.05)                                                         22
                                     Implementing an Interface

            Interface: advanced Java technique
               Not a class
               Set of requirements for a class that wants to conform to the interface


            Compensates for lack of multiple inheritance
               Object can extend a Class implement Interface(1), Interface(2), …


            interface typically includes
                One or more method “signatures”
                Possibly constants


            A class that implements an interface must provide “bodies” for the interface
             methods




(10.19.05)                                                                                  23
                  Interface from ISyE 7210 Simulator: iSimControl.java
   import java.awt.Color;                       //iSimControl
   import java.util.Date;                       public final static int COMPLETE = 6;
   /** Interface that defines methods            public final static int TIME = 7;
      which must be supported by                 public final static int SPEED_FACTOR = 8;
       any class that wants to control
        simulator                                 //methods for simulator
       */                                        public void updateStatus(int status);
   public interface iSimControl
   {                                               /**
        // constants for simulator status             Called by Simulator
     public final static int INITIALIZED = 1;         “global “to initialize instances
     public final static int PAUSED = 2;             */
     public final static int                     public void init(Simulator sim);
        RUNNING_REAL_TIME = 3;
     public final static int                       /**
        RUNNING_FAST_TIME = 4;
                                                     Called by Simulator to update
     public final static int RUNNING = 5;
                                                     the simulation time display
    public final static int COMPLETE = 6;
                                                    */
                                                 public void updateTime(long time);
   //iSimControl (cont’d)
                                                } // end interface iSimControl
(10.19.05)                                                                                   24
                       Interface from ISyE 7210 Simulator: iSort.java

   public interface iSort
   {
     /**
      Provides a comparison capability between two objects
      to be placed on a sorted list.

        @param objectToCompare object which should be compared to this object
        @return true - if this object should come before the comparison object
                  in the sorted list<br>
       @return false - if this object should come after the comparison object
        */
       public boolean isLessThan (iSort objectToCompare);
       public boolean isGreaterThan (iSort objectToCompare);
       public boolean equals (iSort objectToCompare);
   }




(10.19.05)                                                                       25

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:8
posted:8/5/2012
language:English
pages:25