You are on page 1of 8

THREADS

What is a Thread ?
 A thread is nothing but a lightweight process.

 The idea is to achieve parallelism by dividing a process into multiple


threads.

 The Java Virtual Machine allows an application to have multiple


threads of execution running concurrently. Every thread has a priority.
 Threads are independent. If there occurs exception in one thread, it
doesn't affect other threads. It uses a shared memory area.
Uses of Thread
 Threads allow a program to operate more efficiently by doing
multiple things at the same time.
 Threads can be used to perform complicated tasks in the
background without interrupting the main program.
 Threads improve the overall performance of a program.
 When the process is split into many threads, and each thread is
treated as a job, the number of jobs done in the unit time increases.
Therefore, the throughput of the system also increases.
 Resources can be shared between all threads within a process, such
as code, data, and files.
Java Thread Methods
S.N. Modifier and Type Method Description

1 void start() It is used to start the execution of the thread.

2 void run() It is used to do an action for a thread.

It sleeps a thread for the specified amount of


3 static void sleep()
time.

4 int getPriority() It returns the priority of the thread.

5 void setPriority() It changes the priority of the thread.

6 String getName() It returns the name of the thread.

7 void setName() It changes the name of the thread.

8 long getId() It returns the id of the thread.

9 boolean isAlive() It tests if the thread is alive.


10 void suspend() It is used to suspend the thread.

11 void resume() It is used to resume the suspended thread.

12 void stop() It is used to stop the thread.

13 void interrupt() It interrupts the thread.

It tests whether the thread has been


14 boolean isinterrupted()
interrupted.

It tests whether the current thread has been


15 static boolean interrupted()
interrupted.

16 static int activeCount() It returns the number of active threads.

17 Thread.State getState() It is used to return the state of the thread.

It is used to return a string representation of


18 String toString() this thread, including the thread's name,
priority, and thread group.
Life cycle of a Thread
In Java, a thread always exists in any one of the following
states.

• New
• Active
• Blocked / Waiting
• Timed Waiting
• Terminated

You might also like