Breaking News
You are here: Home / Notes / SEM-4 / JAVA / Java Threads

Java Threads

Java Threads

Java Threads

Java Threads

 

♣ Introduction to Threads:

Windows 95 can execute several programs simultaneously; this ability is known as Multitasking. In System’s terminology it is called “Multithreading”.

 

Java programs that contain only a single sequential flow of control is called single-threaded programs. Every program has at least one thread. A Thread is similar to program that have single flow of control. Java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as a separate tiny program (or module) known as thread that runs in parallel to others. A Program that contains multiple flows of control is known as multithreaded program. The main thread is actually the main method module, which is designed to create and start the other threads.

 

Multithreading is a conceptual programming where a program (process) is divided into two or more subprograms (processes), which can be implemented at the same time in parallel. Threads running in parallel do not mean that they actually run at the same time, Since all the threads are running on a single processor, the flow of execution is shared between the threads. The java interpreter handles the switching of control between the threads in such a way that it appears they are running concurrently. Since threads in java are subprograms of a main application program and share the same memory space, they are known as lightweight processes. Multithreading enables programmers to do multiple things at one time. They can divide a long program into threads and executes them in parallel. For Example. We can send tasks such as printing into the background and continue to perform some other task in the foreground, this approach would considerably improve the speed of our programs.

 

♣ The Java Thread Model:

During the life time of a thread, there are many states a thread can enter, They incude:

  1. NewbornState
  2. Runnable State
  3. RunningState
  4. Blocked State
  5. DeadState

java threads

A Thread is always in one of these five states.

 

Newborn State:

When we create a thread object, the thread is born and is said to be in newborn state.

The thread is not yet scheduled for running. At this state, we can do only one of the following things with it.

  1. Scheduled it for running using start() method.
  2. Kill it using stop() method.

It scheduled than it moves to the runnable state.

 

Runnable State:

  • The Runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread had joined the queue of threads that are waiting for execution.
  • If all thread have equal priority, then they are given time slots for execution in round-robin fashion. Ie. First come, First Serve manner. The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to thread is known as time-slicing.
  • However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield() method.

 

Running State:

  • Running means that the processor has given its time to the thread for its execution.
  • The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread.
  • The Running Thread may relinquish its control in one of the following situations.
  1. It has been suspended using suspend() method. The suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time for some reason, but do not want to kill it.
  2. It has been made to sleep, we can made a thread to sleep for a specified time period using the method sleep(time) where time is in milliseconds. This means that the thread is out of queue during this time period. The thread re-enters the runnable as soon as the time period is elapsed.
  3. It has been told to wait until some event occurs. This is done using the wait() method, the thread can be scheduled to run again using notify() method.

 

Blocked State:

  • A thread is said to be blocked when it Is prevented from entering into the runnable state.
  • This happens when the thread is suspended, sleeping or waiting.
  • A blocked state considered “not runnable” but not dead and therefore fully qualified to run again.

 

Dead State:

  • Every thread has a life cycle.
  • A running thread ends its life when it has completed execution its run() method. It is natural death.
  • However, we can kill it by sending a stop message to it at any state thus causing a premature death to it. A thread can be killed as soon as it born, or while it is running, or even when it is in “not runnable” (blocked) condition.

 

The Main Thread:

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins.

  • It is the thread from which other “child” threads will be spawned.
  • Often it must be the last thread to finish execution because it performs various shutdown actions.

Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread.

 

Creating Thread:

  • You can implement the Runnable interface.

import java.lang.*;

 public class Counter implements Runnable

{

          Thread T;

          public void run()

          {

                    ….

          }

}

  • You can extend the Thread class, itself.

import java.lang.*;

public class Counter extends Thread

{

 public void run()

{

….

}

 }

 

Method Return Type Description
currentThread( ) Thread Returns an object reference to the thread in which it is invoked.
getName( ) String Retrieve the name of the thread object or instance.
start( ) void Start the thread by calling its run method.
run( ) void This method is the entry point to execute thread, like the main method for applications.
sleep( ) void Suspends a thread for a specified amount of time (in milliseconds).
isAlive( ) boolean This method is used to determine the thread is running or not.
activeCount( ) int This method returns the number of active threads in a particular thread group and all its subgroups.
interrupt( ) Void The method interrupt the threads on which it is invoked.
yield( ) void By invoking this method the current thread pause its execution temporarily and allow other threads to execute.
join( ) void This  method is invoked on a thread. This is not returned until either the thread has completed or it is timed out respectively.

 

 

♣ Priority of Threads:

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower- priority threads. In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time.) A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower-priority thread.

 

In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.

 

Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to 10 (highest priority given by the constant Thread.MAX_PRIORITY). The default priority is 5 (Thread.NORM_PRIORITY).

 

Constant Description
Thread.MIN_PRIORITY The maximum priority of any thread (an int value of 1)
Thread.MAX_PRIORITY  The minimum priority of any thread (an int value of 10)
Thread.NORM_PRIORITY  The normal priority of any thread (an int value of 5)

 

Eg.:

//Program : Thread Priority Example

public class ThreadPriority extends Thread

   {

    private String threadName;

    ThreadPriority(String threadName)

     {

        this.threadName = threadName;

     }  

    public void run()

          {

        System.out.println("Running [" + threadName + "]");

        for (int i = 1; i <= 10; i++) {

            System.out.println("[" + threadName + "] => " + i);            

            try

              {

                Thread.sleep(500);

            } catch (InterruptedException e)

            {

                   System.out.println(e.toString());

            }

        }

    }

    public static void main(String[] args)

     {

        ThreadPriority thread1 = new ThreadPriority("First");

ThreadPriority thread2 = new ThreadPriority("Second");

        ThreadPriority thread3 = new ThreadPriority("Third");

        ThreadPriority thread4 = new ThreadPriority("Fourth");

        ThreadPriority thread5 = new ThreadPriority("Fifth");

        //

        // set thread1 to minimum priority = 1

        //

        thread1.setPriority(Thread.MIN_PRIORITY);

        // set thread2 to priority 2

        thread2.setPriority(2);

        // set thread3 to normal priority = 5

        thread3.setPriority(Thread.NORM_PRIORITY);

        // set thread4 to priority 8

        thread4.setPriority(8);

        // set thread5 to maximum priority = 10

        thread5.setPriority(Thread.MAX_PRIORITY);

        thread1.start();

        thread2.start();

        thread3.start();

        thread4.start();

        thread5.start();

    }

}

 

setPriority() 

This is method is used to set the priority of thread.

getPriority() 

This method is used to get the priority of thread.

 

♣ Inter Thread Communication:

Java provides a very efficient way through which multiple-threads can communicate with each-other. This way reduces the CPU’s idle time i.e. A process where, a thread is paused running in its critical region and another thread is allowed to enter in the same critical section to be executed.  This technique is known as Interthread communication which is implemented by some methods. These methods are defined in “java.lang”.

Method Description
wait() It indicates the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls method notify() or notifyAll().
notify()  It wakes up the first thread that called wait() on the same object.
notifyAll() Wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

 

 

♣ Synchronization:

When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.

Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.

 

Eg. Without Synchronized Method

class Callme

{

          void call(String msg)

          {

                   System.out.print("[" + msg);

          try

          {

                   Thread.sleep(1000);

          }

          catch(InterruptedException e)

          {

                   System.out.println("Interrupted");

          }

          System.out.println("]");

          }

}

class Caller implements Runnable

{

          String msg;

          Callme target;

          Thread t;

          public Caller(Callme targ, String s)

          {

                   target = targ;

                   msg = s;

                   t = new Thread(this);

                   t.start();

          }

          public void run()

          {

                   target.call(msg);

          }

}

class Synch

{

          public static void main(String args[])

          {

                   Callme target = new Callme();

                   Caller ob1 = new Caller(target, "Hello");

                   Caller ob2 = new Caller(target, "Synchronized");

                   Caller ob3 = new Caller(target, "World");

                   // wait for threads to end

          try {

                   ob1.t.join();

                   ob2.t.join();

                   ob3.t.join();

          } catch(InterruptedException e)

          {

                   System.out.println("Interrupted");

          }

}

}

Output:

Hello[Synchronized[World]

]

]

 

Eg. Using Synchronized Method

class Callme
{

          void call(String msg)

          {

                   System.out.print("[" + msg);

                   try

                   {

                             Thread.sleep(1000);

                   }

                   catch (InterruptedException e)

                   {

                             System.out.println("Interrupted");

                   }

                   System.out.println("]");

          }

}

class Caller implements Runnable

{

          String msg;

          Callme target;

          Thread t;

          public Caller(Callme targ, String s)

          {

                   target = targ;

                   msg = s;

                   t = new Thread(this);

                   t.start();

          }

                   // synchronize calls to call()

          public void run()

          {

                   synchronized(target)  // synchronized block

                   {

                             target.call(msg);

                   }

          }

}

class Synch1

{

          public static void main(String args[])

          {

                   Callme target = new Callme();

                   Caller ob1 = new Caller(target, "Hello");

                   Caller ob2 = new Caller(target, "Synchronized");

                   Caller ob3 = new Caller(target, "World");

                   // wait for threads to end

                   try

                   {

                             ob1.t.join();

                             ob2.t.join();

                             ob3.t.join();

                   }

                   catch(InterruptedException e)

                   {

                             System.out.println("Interrupted");

                   }

          }

}

 

Output:

[Hello] [Synchronized] [World]

Download Paper Solutions from Below Link

About admin

Scroll To Top