Wednesday, November 9, 2016

JAVA Threads.

Basics
  • Threading in JAVA is built-in.
    • Java supports threading natively and at a high level.
    • Java concurrency utilities address common patterns and practices in multithreaded applications and raise them to the level of tangible Java APIs.
    • Not all applications need explicit use of threads or concurrency but most will use some features that is impacted by multithreading.
  • Threads are integral to client side Java APIs
    • GUI, sound.
      • Ex. using separate thread within JVM for drawing.
    • APIs with lots of I/O activities which are slow in nature.
  • Threads are not common and are discouraged on the server side in the context of application servers and web applications.
    • Server environment should control the allocation of CPU time/resources.
  • java.util.concurrent
  • You don't want to put the run() method directly in the object often time.
    • Make an adapter class that serves as the Runnable Object with the run() method and use that to call any method it wants to after the thread is started.
Concept
  • All execution in Java is associated with a Thread object, beginning with "main" thread.
  • New thread is create by java.lang.Thread class.
  • Thread Methods:
    • start
    • run
    • wait
    • sleep
    • notify
    • notifyAll
    • stop is deprecated and don't use it anymore.
  • Since Java has no pointer system to the method to tell it to run, we can't specify one directly. Instead, we use java.lang.Runnable interface to create or mark an object that contains a "runnable" method, which is run().
  • Thread begin its life by executing the run() method in a Runnable object (the target object) that was passed to the thread's constructor.
  • run() must be public, return void, takes no arguments and throws no checked exceptions.
  • Any class that contains an run() method can declare that it implements the Runnable interface.
    • An instance of this class is a runnable object that can serve as the target of a new thread.
Thread States
  • New
  • Runnable
  • Blocked
  • Waiting
  • Terminated

Example
class MyClass implements Runnable {
   boolean choice = ture;

   public void run() {
      while (choice) {
         // do what myClass has to...
      }
   }
}

MyClass item = new MyClass ("message");
thread myThread = new Thread (item);
myThread.start(); // This will cause run() in MyClass to execute

// To make an object to create and handle its own threads so to fit
// OOP concept, the following shows to have the actions in its
// constructor

class MyClass implements Runnable {
   boolean choice = ture;

   Thread myThread;
   public void MyClass (String name) {
      myThread = new Thread(this);
      myThread.start();
   }

   public void run() {
      while (choice) {
         // do what myClass has to...
      }
   }
}


Natual Born Thread Example
class Runner extends Thread {
    boolean running = true;

    public void run() {
        while (! isInterrupted()) {
            // by default, the Thread executes its own run() method when
            // we call the start() method
        }
    }
}

// to call Runner
Runner horse = new Runner ("horse");
horse.start();

// alternatively,
class Runner extends Thread {
    Runner (String name) {
        start();
    }
}

// Use adapter
class Runner {
    public void startRunner() {
        Thread myThread = new Thread (new Runnable () {
            public void run() { doAction(); }
        } );
        myThread.start();
    }

    private void doAction () {
        // do something...
    }
}

// Another way to write the code
new Thread () {
    public void run() { doAction(); }
}.start();


Thread Methods
  • Thread.sleep() -> require try/catch (InterruptedException e)
  • myThread.wait()
  • myThread.join()
  • myThread.interrupt()
  • stop(), suspend() and resume()

More about interrupt() method
Any thread that is not running (hard loop) must be in one of three states - sleep(), wait() or lengthy I/O operation - where it can be flagged to stop by interrupt() method. When a thread is interrupted, its interrupt status flag is set and this can happen at any time. Use isInterrupted() method to test this status like in the example above. You can also use isInterrupted(boolean toClear) as a flag and a signal to clear the interrupt status.

That said, this is historically a weak spot and it may not work correctly in all cases in early JVM, and more often with interrupting I/O calls blocked in a read() or write() method, moving bytes from a file or network. To address this in Java 1.4, a new I/O framework (java.nio) was introduced with one of its goals to address these problems. When the thread associated with an NIO operation is interrupted, the thread wakes up and the I/O stream (called a "channel") is automatically closed. (Check about the NIO package for more information.)


No comments:

Post a Comment