We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Java Threads
Threads allows 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.
Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:Multithreading in Java
Multithreading in Java is a process of executing muhiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing, Multiprocessing and
‘multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, ete
A thread can be in one of the following states:
NEW ~ A thread that has not yet started is inthis tat.
RUNNABLE ~ A thread executing in the Java virtual machine is in this state.
BLOCKED - A thread that is blocked waiting for a monitor lock isin this state.
WAITING — A thread that is waiting indefinitely for another thread to perform a
particular action i in this state.
‘TIMED_WAITING ~ A thread that is waiting for another thread to perform an action
for up to a specified waiting time isin this state.
‘TERMINATED — A thread that has exited isin tis state
/] Java code for
read creation by extending
(/ the Thread clase
clase multithveadingDeno extends Thread {public void runt)
// Displaying the thread thet is sunning
ston (Exception @) |
U1 tmrowing on exception
[Link](*Exception 1s caught")
W/ Main Chass
public static void main (String) args)
inca = 8: // wunber of thzeade
for(int in 7S car SHH
= now moteienreadingneno()¢object. starts
output
Thread 15 is running
Thread 14 ds running
Thread 16 is running
Thread 12 ds running
Thread 11 is running
Thread 13 ds running
Thread 18 is running
Thread 17 ds running