SARAVANAN SIVAJI

Dedicated to JAVA Technologies

Introduction to Java multithreading

Posted by SARAVANAN SIVAJI on April 22, 2009

1. Threads and multithreading

Many programs are sequential. That is, they have a single flow of execution with a beginning, a sequence of tasks to execute, and an end.

In Java, it is possible to create programs with more than one flow of control. So you can write applications that appear to perform more than one task at a time.

For example, you can have a browser application that downloads large files while still allowing you to browse the Web.

Using more than one flow of control in a program is known as multithreading.

The individual sequential flows of control within a program are called threads. A thread’s execution has a beginning, a sequence of tasks, and an end.

Threads are also called execution contexts or lightweight processes.

Is thread is a process? NO!

Threads and processes both have a sequential path of execution. But a thread cannot run on its own, so it’s not a process.

A process can be made up of one or more threads, which may be used to perform simultaneous tasks, such as background calculations.

For example, in a browser program, separate threads enable you to scroll down on a page while the page downloads an image.

Threads in a multithreaded program appear to be running concurrently on separate Java Virtual Machines (JVMs).

Note

The JVM determines which thread should be running.

In fact, the threads are running on a single JVM, with one or more CPUs switching rapidly between the threads’ tasks.

Because the threads running on a single instantiation of the JVM can share objects, it is the responsibility of the programmer to prevent sharing violations.

Question

What is the difference between threads and processes?

Options:

  1. Threads have a sequential path of execution
  2. Threads share memory and resources
  3. Threads are made up of multiple processes

Answer

The difference between threads and processes is that threads share memory and resources.

Option 1 is incorrect. Threads and processes both have a sequential path of execution.

Option 2 is correct. A thread is a process that shares the resources and memory of the process. Threads cannot run on their own.

Option 3 is incorrect. A process is made up of one or more threads, which share the process’s memory and resources.

2. The Thread class

Java has built-in support for multithreading – mostly in the Thread class in the java.lang package. All Java threads correspond to an instance of the Thread class.

The Thread class includes code to

  • start a new thread
  • determine a thread’s state
  • change the priority of a thread
  • pause a thread
start a new thread
Threads are not started directly because threads don’t execute in the same context as the current thread. Instead, you schedule threads to start executing as soon as possible, using the start method of the Thread class.
determine a thread’s state
Threads can be in various states, such as waiting or running. The Thread class provides several methods that enable you to query the state of a thread.
change the priority of a thread
The thread scheduler uses a thread’s priority to determine how much CPU time it should be allocated. Each thread’s priority can be changed to become higher or lower. The Thread class provides a setPriority method that enables you to change the priority of a thread.
pause a thread
Threads can be paused for a period of time, using the static Thread class method, sleep. This enables the thread scheduler to move another thread into the running state.

You can create classes that extend the Thread class, inheriting its methods and variables.

class ThreadA extends Thread {

  public void run() {
    for (int i=0; i<=10; i++) {
      System.out.println("ThreadA is counting: " +i) ;
      try { sleep(500) ;
      }
      catch (InterruptedException e) { }

    }
  }
}

The code in the thread’s run method is the code you want the thread to execute. This can include any tasks that can execute Java statements, such as counting, performing a calculation, calling other methods, or displaying a graphic. A thread’s run method is analogous to a program’s main method.

class ThreadA extends Thread {

  public void run() {
    for (int i=0; i<=10; i++) {
      System.out.println("ThreadA is counting: " +i) ;
      try { sleep(500) ;
      }
      catch (InterruptedException e) { }

    }
  }
}

In the Thread class itself, the run method is empty.

However, when you create a class that extends Thread, you need to write a run method that overrides the version in the Thread class. For example, this run method prints the numbers from 0 to 10 on the screen, printing the text “ThreadA is counting: ” before each number.

The run method has no arguments, returns no results, and should be declared public.

Suppose that you are writing an application that uses multithreading to count upwards and downwards simultaneously.

There are two threads in this application – one that counts up to 25 and one that counts down from 25.

Both the ThreadUp and ThreadDown classes extend the Thread class.

class ThreadUp extends Thread {

You need to create a run method for the ThreadUp class that overrides the run method of the Thread class.

class ThreadUp extends Thread {

  MISSING CODE {
    for (int i=0; i<=25; i++) {
      System.out.println("Up: " +i) ;
      try { sleep(500) ;
      }
      catch (InterruptedException e) { }

    }
  }
}

You type public void run() to create the run method.

The run method of the ThreadUp class counts up to 25, printing out the results to the standard output, and pausing for half a second on each loop.

class ThreadUp extends Thread {

  public void run() {
    for (int i=0; i<=25; i++) {
      System.out.println("Up: " +i) ;
      try { sleep(500) ;
      }
      catch (InterruptedException e) { }

    }
  }
}

The run method in the ThreadDown class counts down from 25, printing the numbers as it counts. It pauses for one second on each loop, using the static Thread.sleep method.

class ThreadDown extends Thread {

  public void run() {
    for (int i=25; i>=0; i--) {
      System.out.println("Down: " +i) ;
      try { sleep(1000) ;
      }
      catch (InterruptedException e) { }

    }
  }
}

In the public class ThreadSample1, you create an instance of the classes ThreadUp and ThreadDown.

//Simple case of two thread counting
//up and down to the screen.
//Use extensions to Thread class

package samples.threads ;

public class ThreadSample1 {

  public static void main (String args[ ]) {
    ThreadUp tUp = new ThreadUp() ;
    ThreadDown tDown = new ThreadDown() ;
    tUp.start() ;
    tDown.start() ;
  }
}

Then you call the start method of the tUp instance and the start method of the tDown instance. The start method queues the thread for execution.

Note

The run method should not be called directly by the code that starts it. If it is called directly, it executes in the same thread, just like any normal method.

When you run the application, both threads operate at the same time, as evident in the section of program output.

C:\ java ThreadSample1
Up: 0
Down: 25
Up: 1
Down: 24
Up: 2
Up: 3
Down: 23
Up: 4
Up: 5
Down: 22
Up: 6
Up: 7
Down: 21
Up: 8
Up: 9
Down: 20
Up: 10
Up: 11
Down: 19
Up: 12
Up: 13
Down: 18
Up: 14
Up: 15
Down: 17
Up: 16

Question

Suppose that you’re writing a browser application using four Java threads, enabling users to download images, print, scroll down on a page, and browse the Web simultaneously. You are using the Thread class to create the relevant threads.

Which line of code defines the DownloadImage class as a Java thread?

Options:

  1. class DownloadImage extends Thread()
  2. class DownloadImage extends Thread {
  3. class Thread extends DownloadImage {

Answer

To define the DownloadImage class as a Java thread, you use the code

class DownloadImage extends Thread {

Option 1 is incorrect. The DownloadImage class needs to extend the Thread class, not a Thread method.

Option 2 is correct. To define the DownloadImage class as a Java thread, the class has to inherit from the Thread class. To do this, you use the extends keyword.

Option 3 is incorrect. The DownloadImage class inherits from the Thread class, so DownloadImage has to extend Thread.

3. The Runnable interface

To create a thread in Java, you don’t always need to write a class that extends the Thread class. An alternative is to write a class that implements the Runnable interface.

The Runnable interface only has one method – public void run() – that you need to implement.

It’s usually better programming practice to use the Runnable interface rather than to extend the Thread class.

Using the Runnable interface instead of subclassing the Thread class enables you to

  • create threads that inherit from classes other than Thread
  • access protected methods and variables of the run method’s superclass
create threads that inherit from classes other than Thread
Java does not directly facilitate multiple inheritance. However, by implementing Runnable, your class is free to inherit from any other class.

This approach is helpful when constructing a class hierarchy. Rather than saying that an object of your class “is a” thread, your class is associated with a thread that executes its code.

access protected methods and variables of the run method’s superclass
Using the run method of the Runnable interface can make it easier for the run method of your class to access protected methods and variables of its superclasses.

Because the run method belongs to a subclass, it gains access to methods and variables denied to non-subclassed classes.

Suppose you want to create a Manager class. You want every instance of the Manager class to be able to run its methods at the same time as the others. To do this, you create a thread.

Instead of creating a subclass of the Thread class, you declare that the Manager class implements the Runnable interface. This enables you to define the Manager class as an Employee subclass that inherits the public variables and methods of Employee.

In this way, you can keep a logical class hierarchy – Manager is a subclass of Employee.

Because Manager is a subclass of Employee, it can also access the protected members of the Employee class, such as the salary variable.

If you are using a class that implements the Runnable interface, you still need to create a Thread object when you want to create a new thread.

You can then pass a reference to the object that implements Runnable to the Thread constructor that takes a Runnable argument.

The object’s run method is then executed when the new thread runs.

Regardless of whether you use the Thread class or the Runnable interface, you do not call the run method directly in the code.

If you do this, the code for your thread will run immediately in the current thread, just as a normal method call would execute.

Instead, you call the thread’s start method, which is a nonstatic method of the Thread class.

If you call methods of the Thread class from an object of a class that implements Runnable, you need to invoke them through a Thread object. However, when you use a subclass of Thread, you can refer to Thread methods implicitly.

The start method registers the thread with the thread scheduler. Depending on your platform, the thread scheduler can be part of the JVM or the operating system.

The thread scheduler determines which thread should be running on the CPU at any given time.

When CPU time is available, the thread’s run method is called automatically.

Suppose that you’re writing an application that has two threads – one that counts up to 25 and one that counts down from 25. Both threads print to the standard output.

public class ThreadSample2 {

  public static void main (String args[ ]) {
    ThreadUp tUp = new ThreadUp () ;
    ThreadDown tDown = new ThreadDown () ;
    Thread tDownThread = new Thread (tDown) ;
    tUpThread.start() ;
    tDownThread.start() ;
  }
}

The ThreadUp and ThreadDown classes that perform the counting task do not extend the Thread class. Instead, they implement the Runnable interface.

class ThreadUp MISSING CODE {

  public void run() {
    for (int i=0; i<=25; i++ ) {
      System.out.println ("Up: " +i) ;
      try { Thread.sleep(500) ;
      }
      catch (InterruptedException e) { }
    }
  }
}

You type implements Runnable to specify that the ThreadUp class implements the Runnable interface.

Each of the classes have a run method that performs the counting and printing to the standard output.

class ThreadUp implements Runnable {

  public void run() {
    for (int i=0; i<=25; i++ ) {
      System.out.println ("Up: " +i) ;
      try { Thread.sleep(500) ;
      }
      catch (InterruptedException e) { }
    }
  }
}

class ThreadDown implements Runnable {

  public void run() {
    for (int i=25; i>=0; i--) {
      System.out.println ("Down: "+i) ;
      try { Thread.sleep(1000) ;
      }
      catch (InterruptedException e) { }    }
  }
}

Because the sleep method is a static member of the Thread class, and not the ThreadUp and ThreadDown classes that implement Runnable, you need to explicitly refer to the Thread class when you call it.

In the public class ThreadSample2, you create an instance each of ThreadUp and ThreadDowntUp and tDown.

//Two threads counting up and down to the screen.
//Use implementations of the Runnable method

public class ThreadSample2 {

  public static void main (String args[ ]) {
    //Construct two instances of Runnable objects
    ThreadUp tUp = new ThreadUp () ;
    ThreadDown tDown = new ThreadDown () ;

    //Create two Threads
    //pass Runnable objects to the constructors
    Thread tUpThread = new Thread (tUp) ;
    Thread tDownThread = new Thread (tDown) ;

The ThreadSample2 class also creates two Thread objects – tUpThread and tDownThread. These objects have constructors that take a Runnable argument.

You need to pass the tUpThread constructor a reference to the tUp object, which implements Runnable.

Now the tUpThread thread, once started, can call the tUp object’s run method to perform the counting action.

//Two threads counting up and down to the screen.
//Use implementations of the Runnable method

public class ThreadSample2 {

  public static void main (String args[ ]) {
    //Construct two instances of Runnable objects
    ThreadUp tUp = new ThreadUp () ;
    ThreadDown tDown = new ThreadDown () ;

    //Create two Threads
    //pass Runnable objects to the constructors
    Thread tUpThread = new Thread (tUp) ;
    Thread tDownThread = new Thread (tDown) ;

The code calls the start methods for tUpThread and tDownThread. The thread scheduler determines when each thread starts, pauses, and resumes execution of its run method.

//Two threads counting up and down to the screen.
//Use implementations of the Runnable method

public class ThreadSample2 {

  public static void main (String args[ ]) {
    //Construct two instances of Runnable objects
    ThreadUp tUp = new ThreadUp () ;
    ThreadDown tDown = new ThreadDown () ;

    //Create two Threads
    //pass Runnable objects to the constructors
    Thread tUpThread = new Thread (tUp) ;
    Thread tDownThread = new Thread (tDown) ;

    //Start the threads
    tUpThread.start() ;
    tDownThread.start() ;

    }
  }

Question

You are creating a thread for a multithread application, so you need to create a class – RunThreads – that needs to have a run method for the thread to call.

Complete the code that specifies that the RunThreads class has a run method.


class RunThreads MISSING CODE {
  public void run() {

Answer

To specify that the RunThreads class has a run method, you use the code

class RunThreads implements Runnable

Summary

You can create Java programs with more than one flow of control. Such programs appear to perform several tasks concurrently. The encapsulation of the flow of control is called a thread. Programs with more than one flow of control are said to be multithreaded. In a multithreaded program, all threads are running on the same Java Virtual Machine (JVM), with one or more CPUs switching rapidly between the threads’ tasks.

Support for multithreading in Java is mostly supplied by the Thread class in the java.lang package. You can create a thread by creating a class that extends the Thread class, and overriding the Thread class’s run method.

A better programming practice is to create classes that implement the Runnable interface, which exposes a single method – public void run(). You create a new thread object and pass that object’s constructor an instance of the class that implements Runnable. The thread then uses the instance’s run method as its execution code.

Advertisement

One Response to “Introduction to Java multithreading”

  1. Veningenmaito said

    Man .. Beautiful .. Amazing .. I’ll bookmark your website and take the feeds additionallyI am satisfied to find so many helpful information here within the put up, we want work out more techniques in this regard, thanks for sharing. . . . . .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.