- Is the sequential flow of control in a program
- Is not a program on its own but runs within a program
- Every program has atleast one thread that is called the primary thread which can be accessed using the currentThread() method
- Is also referred as a lightweight process or execution context.
- The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
- Program can be of two types:
- An application that is made up of only one thread is called a single-threaded application.
- Can perform only one task at a time.
- An application having more than one threads is called a multithreaded application
- Multiple threads in an application run at the same time, perform different tasks, and interact with each other
- Can be created using any of the two ways:
- subclassing the Thread class
- implementing the Runnable interface
- Is used to construct and access individual threads in a multithreaded application
- A separate thread can be created by extending the Thread class
public class <class_name> extends Thread
// class definition...
- Is needed as applets extend from the Applet class and cannot extend from the Thread class to implement threads
- Is implemented and the Applet class is extended in applets
- Has the run() method which contains the functionality of threads
- Syntax :
public class <class_name> extends Applet implements Runnable
// class definition...
Life Cycle of a Thread
- Has the following states:
- DeadNew thread
- Not runnable
Fig 1: Life Cycle of Thread
Fig 2: Life Cycle of Thread with methods
The New Thread State
The Runnable Thread State
- Is entered when the start() method of a thread is invoked
The Not Runnable Thread State
- Is entered if the thread is:
- sleeping – as a result of the sleep() method
- waiting – as a result of the wait() method
- being blocked by another thread – taking care of input-output operations
The Dead Thread State
- Is entered in two situations:
- dies naturally – when the loop in the run() method is complete
- is killed – by assigning null to the thread object
The isAlive() method of the Thread class can be used to determine whether a thread is alive or dead.
Some Important Methods defined in java.lang.Thread are shown in the table:
||Returns an object reference to the thread in which it is invoked.
||Retrieve the name of the thread object or instance.
||Start the thread by calling its run method.
||This method is the entry point to execute thread, like the main method for applications.
||Suspends a thread for a specified amount of time (in milliseconds).
||This method is used to determine the thread is running or not.
||This method returns the number of active threads in a particular thread group and all its subgroups.
||The method interrupt the threads on which it is invoked.
||By invoking this method the current thread pause its execution temporarily and allow other threads to execute.
||This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.
||The maximum priority of any thread (an int value of 10)
||The minimum priority of any thread (an int value of 1)
||The normal priority of any thread (an int value of 5)
The methods that are used to set the priority of thread shown as:
||This is method is used to set the priority of thread.
||This method is used to get the priority of thread.
- Reduces the computation time.
- Improves performance of an application.
- Threads share the same address space so it saves the memory.
- Context switching between threads is usually less expensive than between processes.
- Cost of communication between threads is relatively low.
- 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 (or lock) 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” package and can only be called within synchronized code:
||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().
||It wakes up the first thread that called wait() on the same object.
||Wakes up (Unloack) all the threads that called wait() on the same object. The highest priority thread will run first.
Note: All these methods must be called within a try-catch block.
- Refers to the process of coordinating the actions of multiple threads using synchronized methods or statements
- All objects and classes are associated with a monitor which controls the way in which synchronized methods access an object or a class
- The monitor ensures that only one thread has access to a resource at any given point in time.
- In Java, the threads are executed independently to each other. These types of threads are called as asynchronous threads. But there are two problems may be occur with asynchronous threads.
- Two or more threads share the same resource (variable or method) while only one of them can access the resource at one time.
- If the producer and the consumer are sharing the same kind of data in a program then either producer may produce the data faster or consumer may retrieve an order of data and process it without its existing.
We can prevent a thread from execution by using one of the fallowing methods.
- The thread which is executing yield() causes the current thread temporarily pause and allow other waiting threads of same or high priority to execute.
- If there is no waiting thread, the same thread will execute immediately.
- If all the remaining threads are having low priority, then the same thread once again will execute.
public static native yield();
- If any executing thread calls join method on amy thread t, the current thread will go to the blocked state until it completes.
public final void join() throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms, int nanosec)throws InterruptedException
The following code shows the working of thread synchronization using join () method:
- The thread can interrupt any sleeping/waiting/blocked for joining by the fallowing thread class method.
public void interrupt(); //this is instance method
eg. Its like someone interrupt to person who is sleeping…
- ThreadGroup is used to create a group of threads.
- Whenever it is necessary to manipulate a group of threads as a whole, it is handy to use the ThreadGroup class.
- Service provider Thread
- Use setDeamon(true) to specify
- Use isDaemon() to determine if a thread is Daemon thread
- Often used for resource pools- when there are no more clients, the resource pool is no longer necessary.