Concurrency / Multithreading in Java

There is a mobile optimized version of this page, view AMP Version.

Java provides built-in support for threading tasks in your application, and it’s very simple to implement and use! There are several ways you can setup more threads in your application, I will explain each and give an example.

What is multi-threading and why should I use it?

multi-threading allows you to run another task , something which might take a long time to complete such as connecting to an external server and fetching an XML feed. Doing this in the main thread would result in your application “hanging” while the request was completed.

If you place this process into another thread however, it will happily hang the thread and not your program, by doing this you can allow the user to do other tasks and/or inform them of the current status of there request.

Using another thread for time consuming tasks is very beneficial as no-one likes applications which “hang” because you don't know what is happening or whether the software will recover, the user is just given a frozen screen until the task has finished. However with another thread you can show a loading/waiting sign and even allow the user to perform other tasks while in the background the original task completes.

Creating a Thread

Java defines two ways in which you can create threads from your code, these are:

  1. Implement the Runnable interface.
  2. Extend the main Thread class itself.

 

Create Thread using Runnable:

This is the easiest method to follow and personally I believe to be the best way in which to define more threads.

You can implement Runnable into a class using two different methods, the first method involves creating a second Class under your main class and calling it from your main thread like this:

class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }

 

// Create a new thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Test Thread"); System.out.println("Thread Created: " + t); t.start(); // Start the thread } // This is the entry point for this thread. @Override public void run() { try { for(int i = 500; i > 0; i--) { System.out.println(i); // Let the thread sleep for a while. Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Thread error."); } System.out.println("Exiting thread."); } }

 

The second method for implementing Runnable is the same but a little shorter to implement and neater, It’s a method I also use personally:

class ThreadDemo { public static void main(String args[]) { Thread thr1 = new Thread(NewThread); thr1.start(); } Runnable NewThread = new Runnable() { @Override public void run() { for(int i = 500; i > 0; i—) { System.out.println(i); Thread.sleep(500); } } }; }

 

With both methods you must override the Run( ) method (which is the entry point when the thread is created) and also call the Start( ) method in order to initiate the thread.

 

Create Thread by Extending Main Thread:

The second method is to extend a new class and then create an instance of that class from your main class.

Here is an actual example:

// Create a second thread by extending Thread
class NewThread extends Thread {
   NewThread() {
      // Create a new, second thread
      super("Demo Thread");
      System.out.println("Child thread: " + this);
      start(); // Start the thread
   }

   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
			// Let the thread sleep for a while.
            Thread.sleep(500);
         }
      } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
   }
}

class ExtendThread {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Main Thread: " + i);
            Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

 

With both methods you must override the Run( ) method (which is the entry point when the thread is created) and also call the Start( ) method in order to initiate the thread.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips