0% found this document useful (0 votes)
47 views6 pages

Threads in Java

Threads allow Java programs to execute multiple tasks simultaneously. There are two main ways to create threads in Java: 1) by extending the Thread class and overriding the run() method, or 2) by implementing the Runnable interface and overriding the run() method. Key thread methods include start(), sleep(), yield(), join(), and getPriority(), which control thread execution, pausing, and priorities.

Uploaded by

Nandana Boban
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
47 views6 pages

Threads in Java

Threads allow Java programs to execute multiple tasks simultaneously. There are two main ways to create threads in Java: 1) by extending the Thread class and overriding the run() method, or 2) by implementing the Runnable interface and overriding the run() method. Key thread methods include start(), sleep(), yield(), join(), and getPriority(), which control thread execution, pausing, and priorities.

Uploaded by

Nandana Boban
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

⮚ threads in java

A thread is a:

● Facility to allow multiple activities within a single process


● Referred as lightweight process
● A thread is a series of executed statements
● Each thread has its own program counter, stack and local variables
● A thread is a nested sequence of method calls
● Its shares memory, files and per-process state

thread creation in Java

Thread implementation in java can be achieved in two ways:

1. Extending the java.lang.Thread class


2. Implementing the java.lang.Runnable Interface

Note: The Thread and Runnable are available in the java.lang.* package

1) By extending thread class

● The class should extend Java Thread class.


● The class should override the run() method.
● The functionality that is expected by the Thread to be executed is written in the run()
method.

void start(): Creates a new thread and makes it runnable.


void run(): The new thread begins its life inside this method.

Example:

public class MyThread extends Thread {

public void run(){

System.out.println("thread is running..."); }

public static void main(String[] args) {

MyThread obj = new MyThread();

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.

● The class should implement the Runnable interface


● The class should implement the run() method in the Runnable interface
● The functionality that is expected by the Thread to be executed is put in the run()
method

public class MyThread implements Runnable {

public void run(){

System.out.println("thread is running.."); }

public static void main(String[] args) {

Thread t = new Thread(new MyThread());

t.start(); }

Life cycle of a thread

Threads exist in several states. Following are those states:

The following diagram shows the complete life cycle of a thread.


1) New

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.

● getName() : Obtain thread’s name


● getPriority(): Obtain thread’s priority
● isAlive() : Determine if a thread is still running
● join() : Wait for a thread to terminate
● run() : Entry point for the thread
● sleep(int n): Suspend a thread for a period of time
● start() : Start a thread by calling its run method
● yield(): this method causes the run time to switch the context from the current thread to
the next available runnable thread.
● Resume():used to revive a suspended thread
● Suspend(): it is different from stop() method. It takes the thread and causes it to stop
running and later on can be restored. (by resume()).

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"); } }

You might also like