MULTI-THREADING IN JAVA
Multithreading in Java is a powerful feature that allows concurrent
execution of two or more parts of a program to maximize CPU usage.
Each part of such a program is called a thread, and each thread defines a
separate path of execution.
USES:
Better resource utilization (especially on multi-core processors)
Improved application performance
Enables concurrent programming (e.g., background tasks like file
I/O, UI interaction)
Helps in building responsive applications
A lightweight subprocess; smallest unit of
Thread
processing
Process An independent executing program
Concurrency Executing multiple tasks at the same time
Parallelism Performing multiple operations simultaneously
Creating Threads in Java
class MyThread extends Thread {
public void run() {
[Link]("Thread running: " +
[Link]().getName());
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // starts a new thread, invokes run()
}
}
Implementing the Runnable interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread running: " +
[Link]().getName());
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
[Link]();
}
}
THREAD CLASS IN JAVA:
Class Cake extends Thread
//already inbuilt class with diff methods
{
Public void run()
{
s.o.p(“MIXING INGREDIENTS IN
CAKE”+[Link]().getId());
s.o.p(“BAKING CAKE”+[Link]().getId());
s.o.p(“DECORATING
CAKE”+[Link]().getId());
}
}
Class ThreadBaking
{
PSVM(String []arg)
{
int cakecount=4;
for(int i=0;i<cakecount;i++)
{
Cake c=new Cake();
[Link]();
}
}
o/p: