Tuesday 21 March 2017

Math & Thread, ThreadGroup, and Runnable - Java Tutorials

Math


The Math class contains all the floating-point functions that are used for geometry and trigonometry, as well as several general-purpose methods. Math defines two double constants: E (approximately 2.72) and PI (approximately 3.14).


Transcendental Functions

The following three methods accept a double parameter for an angle in radians and return the result of their respective transcendental function:

static double sin(double arg):  Returns the sine of the angle specified by arg in radians.

static double cos(double arg):  Returns the cosine of the angle specified by arg in radians.

static double tan(double arg):  Returns the tangent of the angle specified by arg in radians.

The next methods take as a parameter the result of a transcendental function and return, in radians, the angle that would produce that result. They are the inverse of their non-arc companions.

static double asin(double arg):  Returns the angle whose sine is specified by arg.

static double acos(double arg):  Returns the angle whose cosine is specified by arg.

static double atan(double arg):  Returns the angle whose tangent is specified by arg.

static double atan2(double x, double y):  Returns the angle whose tangent is x/y.


Exponential Functions

Math defines the following exponential methods:

static double exp(double arg):  Returns e to the arg.

static double log(double arg):  Returns the natural logarithm of arg.

static double pow(double y, double x):  Returns y raised to the x; for example, pow(2.0, 3.0) returns 8.0.

static double sqrt(double arg):  Returns the square root of arg.


Rounding Functions

The Math class defines several methods that provide various types of rounding operations.


The Rounding Methods Defined by Math

static int abs(int arg):  Returns the absolute value of arg.

static long abs(long arg):  Returns the absolute value of arg.

static float abs(float arg):  Returns the absolute value of arg.

static double abs(double arg):  Returns the absolute value of arg.

static double ceil(double arg):  Returns the smallest whole number greater than or equal to arg.

static double floor(double arg):  Returns the largest whole number less than or equal to arg.

static int max(int x, int y):  Returns the maximum of x and y.

static long max(long x, long y):  Returns the maximum of x and y.

static float max(float x, float y):  Returns the maximum of x and y.

static double max(double x, double y):  Returns the maximum of x and y.

static int min(int x, int y):  Returns the minimum of x and y

static long min(long x, long y):  Returns the minimum of x and y.

static float min(float x, float y):  Returns the minimum of x and y.

static double min(double x, double y):  Returns the minimum of x and y.

static double rint(double arg):  Returns the integer nearest in value to arg.

static int round(float arg):  Returns arg rounded up to the nearest int.

static long round(double arg):  Returns arg rounded up to the nearest long.


Miscellaneous Math Methods

In addition to the methods just shown, Math defines the following methods:

      static double IEEEremainder(double dividend, double divisor)
      static double random( )
      static double toRadians(double angle)
      static double toDegrees(double angle)

IEEEremainder( ) returns the remainder of dividend/divisor. random( ) returns a pseudorandom number. This value will be between 0 and 1. Most of the time, you will use the Random class when you need to generate random numbers. The toRadians( ) method converts degrees to radians. toDegrees( ) converts radians to degrees. The last two methods were added by Java 2.

Here is a program that demonstrates toRadians( ) and toDegrees( ):

  // Demonstrate toDegrees() and toRadians().
  class Angles {
    public static void main(String args[]) {
      double theta = 120.0;

      System.out.println(theta + " degrees is " +
                         Math.toRadians(theta) + " radians.");

      theta = 1.312;
      System.out.println(theta + " radians is " +
                         Math.toDegrees(theta) + " degrees.");
    }
  }

The output is shown here.

  120.0 degrees is 2.0943951023931953 radians.
  1.312 radians is 75.17206272116401 degrees.




Thread, ThreadGroup, and Runnable

The Runnable interface and the Thread and ThreadGroup classes support multithreaded programming. Each is examined next. An overview of the techniques used to manage threads, implement the Runnable interface.


The Runnable Interface

The Runnable interface must be implemented by any class that will initiate a separate thread of execution. Runnable only defines one abstract method, called run( ), which is the entry point to the thread. It is defined like this:

      abstract void run( )

Threads that you create must implement this method.


Thread

Thread creates a new thread of execution. It defines the following commonly used constructors:

      Thread( )
      Thread(Runnable threadOb)
      Thread(Runnable threadOb, StringthreadName)
      Thread(String threadName)
      Thread(ThreadGroup groupOb, Runnable threadOb)
      Thread(ThreadGroup groupOb, Runnable threadOb, String threadName)
      Thread(ThreadGroup groupOb, String threadName)

threadOb is an instance of a class that implements the Runnable interface and defines where execution of the thread will begin. The name of the thread is specified by threadName. When a name is not specified, one is created by the Java Virtual Machine. groupOb specifies the thread group to which the new thread will belong. When no thread group is specified, the new thread belongs to the same group as the parent thread.

The following constants are defined by Thread:

      MAX_PRIORITY
      MIN_PRIORITY
      NORM_PRIORITY

As expected, these constants specify the maximum, minimum, and default thread priorities. In versions of Java prior to 2, Thread also included the methods stop( ), suspend( ), and resume( ). However, these have been deprecated by Java 2 because they were inherently unstable. Also deprecated by Java 2 is countStackFrames( ), because it calls suspend( ).


The Methods Defined by Thread

static int activeCount( ):  Returns the number of threads in the group to which the thread belongs.

void checkAccess( ):  Causes the security manager to verify that the current thread can access and/or change the thread on which checkAccess( ) is called.

static Thread currentThread( ):  Returns a Thread object that encapsulates the thread that calls this method.

void destroy( ):  Terminates the thread.

static void dumpStack( ):  Displays the call stack for the thread.

static int enumerate(Thread threads[ ]):  Puts copies of all Thread objects in the current thread’s group into threads. The number of threads is returned.

ClassLoader getContextClassLoader( ):  Returns the class loader that is used to load classes and resources for this thread. (Added by Java 2)

final String getName( ):  Returns the thread’s name.

final int getPriority( ):  Returns the thread’s priority setting.

final ThreadGroup getThreadGroup( ):  Returns the ThreadGroup object of which the invoking thread is a member.

static boolean holdsLock(Object ob):  Returns true if the invoking thread owns the lock on ob. Returns false otherwise. (Added by Java 2, version 1.4)

void interrupt( ):  Interrupts the thread.

static boolean interrupted( ):  Returns true if the currently executing thread has been scheduled for interruption. Otherwise, it returns false.

final boolean isAlive( ):  Returns true if the thread is still active. Otherwise, it returns false.

final boolean isDaemon( ):  Returns true if the thread is a daemon thread (one that is part of the Java run-time system). Otherwise, it returns false.

boolean isInterrupted( ):  Returns true if the thread is interrupted. Otherwise, it returns false.

final void join( ) throws InterruptedException:   Waits until the thread terminates.

final void join(long milliseconds) throws InterruptedException:   Waits up to the specified number of milliseconds for the thread on which it is called to terminate.

final void join(long milliseconds, int nanoseconds) throws InterruptedException:  Waits up to the specified number of milliseconds plus nanoseconds for the thread on which it is called to terminate.

void run( ):  Begins execution of a thread.

void setContextClassLoader(ClassLoader cl):  Sets the class loader that will be used by the invoking thread to cl. (Added by Java 2)

final void setDaemon(boolean state):  Flags the thread as a daemon thread.

final void setName(String threadName):  Sets the name of the thread to that specified by threadName.

final void setPriority(int priority):  Sets the priority of the thread to that specified by priority.

static void sleep(long milliseconds) throws InterruptedException:   Suspends execution of the thread for the specified number of milliseconds.

static void sleep(long milliseconds, int nanoseconds) throws InterruptedException: Suspends execution of the thread for the specified number of milliseconds plus nanoseconds.

void start( ):  Starts execution of the thread.

String toString( ):  Returns the string equivalent of a thread.

static void yield( ):  The calling thread yields the CPU to another thread.


ThreadGroup

ThreadGroup creates a group of threads. It defines these two constructors:

      ThreadGroup(String groupName)
      ThreadGroup(ThreadGroup parentOb, String groupName)

For both forms, groupName specifies the name of the thread group. The first version
creates a new group that has the current thread as its parent. In the second form, the
parent is specified by parentOb.

In versions of Java prior to 2, ThreadGroup also included the methods stop( ), suspend( ), and resume( ). These have been deprecated by Java 2 because they were inherently unstable.

Thread groups offer a convenient way to manage groups of threads as a unit. This is particularly valuable in situations in which you want to suspend and resume a number of related threads. For example, imagine a program in which one set of threads is used for printing a document, another set is used to display the document on the screen, and another set saves the document to a disk file. If printing is aborted, you will want an easy way to stop all threads related to printing. Thread groups offer this convenience. The following program, which creates two thread groups of two threads each, illustrates this usage:


The Methods Defined by ThreadGroup

int activeCount( ):  Returns the number of threads in the group plus any groups for which this thread is a parent.

int activeGroupCount( ):  Returns the number of groups for which the invoking thread is a parent.

final void checkAccess( ):  Causes the security manager to verify that the invoking thread may access and/or change the group on which checkAccess( ) is called.

final void destroy( ):  Destroys the thread group (and any child groups) on which it is called.

int enumerate(Thread group[ ]):  The threads that comprise the invoking thread group are put into the group array.

int enumerate(Thread group[ ], boolean all):  The threads that comprise the invoking thread group are put into the group array. If all is true, then threads in all subgroups of the thread are also put into group.

int enumerate(ThreadGroup group[ ]) The subgroups of the invoking
thread group are put into the
group array.

int enumerate(ThreadGroup group[ ], boolean all):   The subgroups of the invoking thread group are put into the group array. If all is true, then all subgroups of the subgroups (and so on) are also put into group.

final int getMaxPriority( ):  Returns the maximum priority setting for the group.

final String getName( ):  Returns the name of the group.

final ThreadGroup getParent( ):  Returns null if the invoking ThreadGroup object has no parent. Otherwise, it returns the parent of the invoking object.

final void interrupt( ):  Invokes the interrupt( ) method of all threads in the group. (Added by Java 2)

final boolean isDaemon( ):  Returns true if the group is a daemon group. Otherwise, it returns false.

boolean isDestroyed( ):  Returns true if the group has been destroyed. Otherwise, it returns false.

void list( ):  Displays information about the group.

final boolean parentOf(ThreadGroup group):  Returns true if the invoking thread is the parent of group (or group, itself). Otherwise, it returns false.

final void setDaemon(boolean isDaemon):  IfisDaemon is true, then the invoking group is flagged as a daemon group.

final void setMaxPriority(int priority):  Sets the maximum priority of the invoking group to priority.

String toString( ):  Returns the string equivalent of the group.

void uncaughtException(Thread thread, Throwable e):   This method is called when an exception goes uncaught.


  // Demonstrate thread groups.
  class NewThread extends Thread {
    boolean suspendFlag;

    NewThread(String threadname, ThreadGroup tgOb) {
      super(tgOb, threadname);
      System.out.println("New thread: " + this);
      suspendFlag = false;
      start(); // Start the thread
    }

    // This is the entry point for thread.
    public void run() {
      try {
        for(int i = 5; i > 0; i--) {
          System.out.println(getName() + ": " + i);
          Thread.sleep(1000);
          synchronized(this) {
            while(suspendFlag) {
              wait();
            }
          }
        }
      } catch (Exception e) {
        System.out.println("Exception in " + getName());
      }
      System.out.println(getName() + " exiting.");
    }

    void mysuspend() {
      suspendFlag = true;
    }

    synchronized void myresume() {
      suspendFlag = false;
      notify();
    }
  }

  class ThreadGroupDemo {
    public static void main(String args[]) {
      ThreadGroup groupA = new ThreadGroup("Group A");
      ThreadGroup groupB = new ThreadGroup("Group B");

      NewThread ob1 = new NewThread("One", groupA);
      NewThread ob2 = new NewThread("Two", groupA);
      NewThread ob3 = new NewThread("Three", groupB);
      NewThread ob4 = new NewThread("Four", groupB);

      System.out.println("\nHere is output from list():");
      groupA.list();
      groupB.list();
      System.out.println();

      System.out.println("Suspending Group A");
      Thread tga[] = new Thread[groupA.activeCount()];
      groupA.enumerate(tga); // get threads in group
      for(int i = 0; i < tga.length; i++) {
        ((NewThread)tga[i]).mysuspend(); // suspend each thread
      }

      try {
        Thread.sleep(4000);
      } catch (InterruptedException e) {
        System.out.println("Main thread interrupted.");
      }

      System.out.println("Resuming Group A");
      for(int i = 0; i < tga.length; i++) {
        ((NewThread)tga[i]).myresume(); // resume threads in group
      }

      // wait for threads to finish
      try {
        System.out.println("Waiting for threads to finish.");
        ob1.join();
        ob2.join();
        ob3.join();
        ob4.join();
      } catch (Exception e) {
        System.out.println("Exception in Main thread");
      }

      System.out.println("Main thread exiting.");
    }
  }

Sample output from this program is shown here:

  New thread: Thread[One,5,Group A]
  New thread: Thread[Two,5,Group A]
  New thread: Thread[Three,5,Group B]
  New thread: Thread[Four,5,Group B]
  Here is output from list():
  java.lang.ThreadGroup[name=Group A,maxpri=10]
    Thread[One,5,Group A]
    Thread[Two,5,Group A]
  java.lang.ThreadGroup[name=Group B,maxpri=10]
    Thread[Three,5,Group B]
    Thread[Four,5,Group B]
  Suspending Group A
  Three: 5
  Four: 5
  Three: 4
  Four: 4
  Three: 3
  Four: 3
  Three: 2
  Four: 2
  Resuming Group A
  Waiting for threads to finish.
  One: 5
  Two: 5
  Three: 1
  Four: 1
  One: 4
  Two: 4
  Three exiting.
  Four exiting.
  One: 3
  Two: 3
  One: 2
  Two: 2
  One: 1
  Two: 1
  One exiting.
  Two exiting.
  Main thread exiting.

Inside the program, notice that thread group A is suspended for four seconds. As the output confirms, this causes threads One and Two to pause, but threads Three and Four continue running. After the four seconds, threads One and Two are resumed. Notice how thread group A is suspended and resumed. First, the threads in group A are obtained by calling enumerate( ) on group A. Then, each thread is suspended by iterating through the resulting array. To resume the threads in A, the list is again traversed and each thread is resumed. One last point: this example uses the recommended Java 2 approach to suspending and resuming threads. It does not rely upon the deprecated methods suspend( ) and resume( ).

No comments:

Post a Comment