Introduction to Threads

Threads
Java is a multithreaded application that allows multiple thread execution at any particular time. In a single-threaded application, only one thread is executed at a time because the application or program can handle only one task at a time.
For example, a single-threaded application may allow for the typing of words. However, this single thread requires an additional single thread allowing for the recording of keystrokes in order to type the words. Thus, a single-threaded application records the keystrokes, allowing the next single-threaded application (the typing of words) to follow.
However, a multithreaded application allows for the handling of both tasks (recording and typing the keystrokes) within one application.
Understand threads execution in java
1. Threads always run in sequence , If there are many threads and we want to run them one thread will run at a time only.
2. If due to any condition any thread is blocked or destroyed, other threads have ability to run.
3. Threads unlike processes are not independent of each other, they depend on each other.
4. Threads unlike processes can share their resource with each other, that is two threads can access the same memory blocks.
5. Threads unlike processes are always in position to support each other.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

* New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
* Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
* Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
* Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
* Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.
Example: -
import java.lang.*;
public class ThreadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("Admin Thread");
// set thread priority to 1
t.setPriority(1);
// prints the current thread
System.out.println("Thread = " + t);
int count = Thread.activeCount();
System.out.println("currently active threads = " + count);
}
}
C:\java>javac ThreadDemo.java
C:\java>java ThreadDemo
Thread = Thread[Admin Thread,1,main]
currently active threads = 1
Multithreading has many advantages over Multiprocessing
* Threads are lightweight compared to processes
* Threads share the same address space and therefore can share both data and code
* Context switching between threads is usually less expensive than between processes
* Cost of thread intercommunication is relatively low that that of process intercommunication
* Threads allow different tasks to be performed concurrently.
Thread Creation
There are two ways to create thread in java;
1. Implement the Runnable interface (java.lang.Runnable)
2. By Extending the Thread class (java.lang.Thread)
1. Implement the Runnable interface (java.lang.Runnable)
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
Example: -
class RunnableThread implements Runnable {
Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}
C:\java>javac RunnableExample.java
C:\java>java RunnableExample
thread3
Thread[thread3,5,main]
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[main,5,main]
2. By Extending the Thread class (java.lang.Thread)
The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.
Example: -
class XThread extends Thread {
XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}
class ThreadExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new XThread(), "thread1");
Thread thread2 = new Thread(new XThread(), "thread2");
// The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread("thread5");
//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}
C:\java>javac ThreadExample.java
C:\java>java ThreadExample
Thread[thread5,5,main]
thread5
thread1
thread2
Thread-2
Thread-3
Thread[main,5,main]
Thread Methods: -
Following is the list of important methods available in the Thread class.-
SN Methods with Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

Invoking one of the static methods performs the operation on the currently running thread.
SN Methods with Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.


Free Web Hosting