Threads in Java
Threads in Java
A thread is a:
Note: The Thread and Runnable are available in the java.lang.* package
Example:
System.out.println("thread is running..."); }
obj.start();
}
2) By Implementing Runnable interface
It is the easiest way to create a thread by implementing Runnable. One can create a
thread on any object by implementing Runnable. To implement a Runnable, one has only to
implement the run method.
public void run()
In this method, we have the code which we want to execute on a concurrent
thread. In this method, we can use variables, instantiate classes, and perform an action like
the same way the main thread does. The thread remains until the return of this method. The
run method establishes an entry point to a new thread.
System.out.println("thread is running.."); }
t.start(); }
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4Waiting/ Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Dead(Terminated)
A thread is in terminated or dead state when its run() method exits.
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 are very much platform dependent.
import java.lang.*;
class ThreadDemo extends Thread
{
public void run() {
System.out.println("Inside run method");
} public static void main(String[]args){
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
System.out.println("t1 thread priority : " + t1.getPriority());
System.out.println("t2 thread priority : " + t2.getPriority());
t1.setPriority(2);
t2.setPriority(5);
System.out.println("t1 thread priority : " + t1.getPriority());
System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println(Thread.currentThread().getName());
System.out.println("Main thread priority : " + Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : " + Thread.currentThread().getPriority()); } }
Output:
t1 thread priority : 5
t2 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
Main thread priority : 5
Main thread priority : 10
⮚ The Thread class defines several methods that help manage threads.
yield():
Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and
starts its execution and thread t2 and t3 are in Ready/Runnable state. Completion time for thread
t1 is 5 hour and completion time for t2 is 5 minutes. Since t1 will complete its execution after
5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one
thread is taking too much time to complete its execution, we need a way to prevent execution
of a thread in between if something important is pending. yeild() helps us in doing so.
yield() basically means that the thread is not doing anything particularly important and if any
other threads or processes need to be run, they should run. Otherwise, the current thread will
continue to run.
Example
import java.lang.*;
class MyThread extends Thread
{
public void run() {
for (int i=0; i<5 ; i++)
System.out.println(Thread.currentThread().getName() + " in control");
}}
public class yieldDemo
{ public static void main(String[]args)
{ MyThread t = new MyThread();
t.start();
for (int i=0; i<5; i++)
{
// Control passes to child thread
Thread.yield();
// After execution of child Thread
// main thread takes over
System.out.println(Thread.currentThread().getName() + " in control");
} }}
Output
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
main in control
main in control
main in control
main in control
main in control
sleep():
This method causes the currently executing thread to sleep for the specified number of
milliseconds, subject to the precision and accuracy of system timers and schedulers.
import java.lang.*;
public class SleepDemo implements Runnable
{ Thread t;
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try
{ // thread to sleep for 1000 milliseconds
Thread.sleep(1000); }
catch (Exception e)
{ System.out.println(e);
}}}
public static void main(String[] args) throws Exception
{ Thread t = new Thread(new SleepDemo());
t.start();
Thread t2 = new Thread(new SleepDemo());
t2.start();
}}
o/p
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
join() method
The join() method is used to hold the execution of currently running thread until the
specified thread is dead
import java.lang.*;
class MyThread extends Thread
{
public void run() {
for (int i=0; i<5 ; i++)
System.out.println(Thread.currentThread().getName() + " in control");
}}
public class joinDemo
{ public static void main(String[]args)
{ MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();}
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace(); }
t3.start();
try {
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();}
System.out.println("All threads are executed"); } }