Saturday, October 20, 2018

Java Threading

Implement a class that implements IRunnable (requires run() method

// This code can reside inside or outside the class that implements IRunnable
Thread thread = new Thread(<instance of class that implements IRunnable)


thread.start();  // executes the run() method

public class SomeProcess implements Runnable{

Thread runner;

SomeProcess (){
  if (runner == null){
    runner = new Thread(this); // look for Run method in this class
    runner.start();  // executes the Run method
  }
}

public void Run (){
   Thread thisThread = Thread.currentThread();

   // thread terminates when Run() ends
}

OR

// set this.runner to null to terminate the thread by setting 
//  this.runner to null from anywhere else
// 
public void Run (){
   Thread thisThread = Thread.currentThread();
   while (runner == thisThread){

   }
   // thread terminates when Run() ends
}

}

Creating with an anonymous inner class

new Runnable() {
  public void run(){
  }}
}

Creating with a Closure

There is only required method for Runnable so we can define as Closure/lambda
Runnable runner = () ->  { // code for Run method }