AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1345&pId=-1
Multithreading in Java
page
by Debjani Mallick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 27105/ 59

Introduction

Multithreading is a process that allows a multitasking operating system to work on different portions, i.e., threads of a single application smoothly. In other words, it can be described as a form of parallelism where multiple threads can run in a concurrent manner.

Java supports programming for multitasking environment where the CPU can perform different tasks simultaneously. The multitasking environment can execute in two ways.

·         Process based multitasking

·         Thread based multitasking

Process based multitasking – A process is a program which is currently acquiring the CPU time and, hence, it is the currently executing the program. The process based multitasking can execute two different processes simultaneously where the processes are running under different locations. For example, we can write some text using editor, at the same time some other software can play music.

Thread based multitasking – Thread is the smallest unit of dispatchable codes. In a thread based multitasking environment, one program can perform two different tasks. Therefore, we can say that two different tasks are executing. For example, we can print a word document at the same time we can do some typing.

The threading concept says that the different blocks of the same program can be executed concurrently. In Java, for implementing threading, there is a built-in class called Thread. There are various methods supported by Thread class.

·         setName() – It takes a string argument and assigns it as the name of the thread.

·         getName() – It returns a string which indicates the name of the thread though it does not take any argument.

·         sleep() – It accepts an argument of long integer type and it tells the thread to wait for certain milliseconds.

·         isAlive() – It determines whether a thread has completed its execution or not. It returns true if the thread is still executing.

·         join() – This function tells a thread to wait for completion of another thread.

·         start() – It invokes the threads or starts the thread.

·         run() – To run a thread, we need this. It contains the codes which are executed when a thread is running.

Main Thread

It is the entry point from where the execution begins. Every Java program contains at least one thread which is called the main thread. It is the entry point from where the execution begins and from the main thread, we can start other threads. By default there is a main thread existing in every Java program.

Listing 1

class threadDemo
{
  public static void main(String a[])
  {
    Thread t = Thread.currentThread();
    System.out.println("Current Thread: " + t);
    t.setName("Demo");
    System.out.println("After changing the name, the thread is " + t);
    for (int i = 5; i > 0; i--)
    {
      System.out.println("Current Thread: " + i);
      t.sleep(1000);
    }
  }
}

While doing a multithreading program, the main thread should terminate only after all the other threads get terminated.

Creating Child Threads

We can create child threads by:

·         Creating a class that implements Runnable (Runnable is an interface)

·         Creating a class which extends Thread class

To create child thread using Runnable interface:

·         First declare the class which implements Runnable

·         Declare an object reference of thread class as an instance of the implementing class

·         Invoke constructor of the thread class within the constructor of implementing class

The syntax of the constructor will be as follows.

Listing 2

Thread(this,string);

Invoke the start method to actually run the thread.

Define the run method.

Listing 3

import java.lang.*;
class myThread implements Runnable
{
  Thread t;
  public myThread();
  {
    t = new Thread(this, "child thread");
    System.out.println("Starting the child");
    t.start();
  }
  public void run()
  {
    Try
    {
      for (int i = 5; i > 0; i--)
      {
        System.out.println("Child Thread:" + i);
        Thread.sleep(1000);
      }
 
    }
    catch (InterruptedException e)
    {
      System.out.println();
    }
    System.out.println("Finishing the thread");
 
  }
}
 
class threadDemo
{
  myThread = new myThread();
  Try
  {
    for (int i = 5; i > 0; i--)
    {
      System.out.println("Main Thread:" + i);
      Thread.sleep(2000);
    }
  }
  catch (InterruptedException e)
  {
    System.out.println();
  }
  System.out.println("Finishing the thread");
}
}

To create child thread using Thread interface, insert the following.

Listing 4

import java.lang.*;
class myThread extends Thread
{
  public void run()
  {
    … … … … … … … … …
  }
}

This methodology should be implemented only if the class which needs to be executed does not require to be extended from another class ever.

Suspending and Resuming a Thread

Run the following code to suspend and resume a thread.

Listing 5

class myThread implements Runnable
{
  String threadName;
  Thread t;
  Public myThread(String name)
  {
    threadName = name;
    t = new Thread(threadName);
    System.out.println(“The value of name: ” + name);
    t.start();
  }
  public void run()
  {
    try
    {
      for (int i = 15; i >= 1; i--)
      {
        System.out.println(“Thread ” + t + “Count: ” + i);
        t.sleep(200);
 
      }
    }
    catch (InterruptedException e)
    {
      System.out.println("Thread Interrupted”);
    }
    System.out.println("Terminating”+t);
  }
}
 
class demo
{
  public static void main(String a[])
  {
    myThread T1 = new myThread(“First ”); myThread T2 = new myThread(“Second ”)
      ; Try
    {
      Thread.sleep(1000); T1.t.suspend(); System.out.println(“Thread ” + T1 +
        “suspended ”); Thread.sleep(1000); T1.t.resume(); System.out.println
        (“Thread ” + T1 + “resumed ”); T2.t.suspend(); System.out.println
        (“Thread ” + T2 + “suspended ”); Thread.sleep(1000); T2.t.resume();
    }
    catch (InterruptedException e)
    {
      System.out.println("Thread Interrupted”);
    }
    Try
    {
      T1.t.join(); T2.t.join();
    }
    catch (InterruptedException e)
    {
      System.out.println("Thread Interrupted”);
    }
    System.out.println(“Finishing main thread ”);
  }
}

The threads can communicate between each other by passing some messages. When multiple threads are concurrently executed, a thread can be suspended. One thread can suspend another thread. To do so, the thread must invoke suspend() method of thread class. Once suspended, the threads can be resumed also. The suspended thread can be resumed with the help of another thread by invoking resume() method. Similarly, the execution of the thread can be forcibly terminated by another thread with the help of stop() function. However, all these functions are deprecated in Java 2. Whenever a thread is suspended, it may lead to a serious problem. If a thread is using a resource and another thread is waiting for that thread to release the resource, then if the thread which has currently acquired the resource is suspended, the resource cannot be released. It may lead to a dead lock situation. Similarly, the resume() method is also ignored in Java 2 though it does not lead to any problem, but still it cannot be used without suspend() method. In Java 2, there are some other methods which when used can suspend or resume a thread. Those are wait(), notify() and notifyall(). These methods must be called through the extending class or implementing class. When the wait() method is invoked, then the thread must release the resources and suspend temporarily. The notify() method is used to restart the threads which are in waiting state (the first one in queue). The notifyall() method will awake all the threads that have been in the waiting state. The same program can be written as shown below without using the suspend() and resume() method.

Listing 6

class myThread implements Runnable
{
  String threadName;
  Thread t;
  public myThread(String name)
  {
    threadName = name;
    t = new Thread(threadName);
    flag = false;
    System.out.println(“The value of name: ” + name);
    t.start();
  }
  public void mySuspend()
  {
    flag = true;
  }
  public void myResume()
  {
    flag = false;
    t.notify();
  }
  public void run()
  {
    try
    {
      for (int i = 15; i >= 1; i--)
      {
        System.out.println(“Thread ” + t + “Count: ” + i);
        t.sleep(200);
        while (flag)
        {
          t.wait();
        }
      }
    }
    catch (InterruptedException e)
    {
      System.out.println("Thread Interrupted”);
    }
    System.out.println("Terminating”+t);
  }
}
 
class demo
{
  public static void main(String a[])
  {
    myThread T1 = new myThread(“First ”); myThread T2 = new myThread(“Second ”)
      ; Try
    {
      Thread.sleep(1000); T1.mySuspend(); System.out.println(“Thread ” + T1 +
        “suspended ”); Thread.sleep(1000); T1.myResume();
    }
    catch (InterruptedException e)
    {
      System.out.println("Thread Interrupted”);
    }
    Try
    {
      T1.t.join(); T2.t.join();
    }
    catch (InterruptedException e)
    {
      System.out.println("Thread Interrupted”);
    }
    System.out.println(“Finishing main thread ”);
  }
}
Conclusion

In my next article I will discuss file handling and exception handling in java.

By Debjani Mallick


Product Spotlight
Product Spotlight 

©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-11-29 10:05:10 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search