17.4 Thread Definition


17.4 Thread Definition

There are two ways to define threads. One way is to define a class that inherits class Thread; another way is to define a class that implements the Runnable interface. The first way to use threads is to derive a subclass from the Thread class and override the run() method. The following is a simple portion of code that illustrates the first method:

       description          This class defines a thread. */       class MyThread inherits Thread is       public       description         This is the main body of the thread definition.         */       void function run is              //              // do something;              // When this method returns,              // the thread terminates       endfun run       endclass MyThread 

To create a thread and start its execution, the following portion of code is included in the main class of an application program:

       objects          object mt of class MyThread          ...       begin          ...          create mt of class MyThread          call start of mt    // start running the thread          ... 

The second technique to define a class that implements the Runnable interface and override the run() method. The following is a simple portion of code that illustrates this thechnique:

       description         This class also defines a thread. */       class MyThreadb inherits OtherClass                                 implements Runnable is       public       description          This is the main body of the thread definition.          */       void function run is               //               // do something;               // When this method returns,               // the thread terminates       endfun run       endclass MyThreadb 

The advantage of the second technique is that there is no need to inherit class Thread. To create a thread and start its execution, the following portion of code is included in the main class of an application program:

       objects         object ms of class MyThreadb         object myth of class Thread         ...       begin         ...         create ms of class MyThreadb         create myth of class Thread using ms         call start of myth 




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net