KEMBAR78
Multithreading | PDF | Thread (Computing) | Process (Computing)
0% found this document useful (0 votes)
12 views18 pages

Multithreading

The document provides an overview of multithreading in Java, explaining the concept of threads, their states, and the lifecycle of the main thread. It also discusses daemon threads, thread creation methods, synchronization techniques, and safe practices for suspending and stopping threads. Key examples illustrate how to create and manage multiple threads while ensuring data integrity through synchronization.

Uploaded by

Sheryl Arulini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views18 pages

Multithreading

The document provides an overview of multithreading in Java, explaining the concept of threads, their states, and the lifecycle of the main thread. It also discusses daemon threads, thread creation methods, synchronization techniques, and safe practices for suspending and stopping threads. Key examples illustrate how to create and manage multiple threads while ensuring data integrity through synchronization.

Uploaded by

Sheryl Arulini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Multithreading

Java Thread Model

• Multithreading is the ability of a CPU (or a single core in a


multicore processor) to execute multiple threads
concurrently.
• A thread is a lightweight subprocess, and multiple threads
within a process share the same memory space.
• A thread is the smallest unit of execution within a process.
In Java, threads are represented by instances of the Thread
class or by implementing the Runnable interface.
• Threads can execute code independently of each other,
allowing for concurrent execution of tasks.
2
Java Thread
Model

3
Thread States

Threads in Java can be in various states, each representing a different


stage in their lifecycle. These states include:
• NEW: The thread has been created but has not yet started.
• RUNNABLE: The thread is executing its task or is ready to run if it's in
the queue.
• BLOCKED: The thread is waiting for a monitor lock to enter a
synchronized block or method.
• WAITING: The thread is waiting indefinitely for another thread to
perform a particular action.
• TIMED_WAITING: The thread is waiting for another thread to perform a
particular action, but with a specified maximum time.
• TERMINATED: The thread has completed its task and terminated.
4
The Main Thread

• The "main" thread in Java is the thread that runs when a Java program starts
its execution. It's the thread responsible for executing the main() method of
the program.
• When you run a Java application, the Java Virtual Machine (JVM) starts the
main thread, and the execution of your program begins from there.
1. Entry Point:
The main() method serves as the entry point for Java applications. It's where
the main thread begins its execution.
2. Lifecycle:
The main thread follows the standard thread lifecycle, starting in the "NEW"
state when the program starts and transitioning through "RUNNABLE" to
"TERMINATED" when the main() method completes or when the program exits.
5
The Main Thread – Cont’D
3. Execution:
• The main thread executes the instructions specified in the main()
method. It can create and manage other threads as needed, perform
initialization tasks, and coordinate the overall flow of the program.
4. Joining:
• You can use the join() method to make the main thread wait for another
thread to complete its execution. This is often used when you want to
ensure that certain tasks are completed before the program terminates.
5. Termination:
• When the main() method completes or when the program explicitly
terminates (e.g., by calling System.exit()), the main thread terminates,
and the program exits. Any remaining threads, including daemon
threads, are abruptly terminated.
6
Daemon Thread
• In Java, a daemon thread is a special type of thread that runs in the background,
providing services to other threads or performing tasks that do not require continuous
execution. Unlike user threads, which are regular threads created by the application,
daemon threads are treated as service providers and are terminated by the JVM when
there are no longer any user threads running, even if they are still executing.
• Here are some key characteristics of daemon threads:
1. Background Tasks:
• Daemon threads are often used for background tasks, such as garbage collection,
monitoring, or I/O operations. They typically perform tasks that can run independently
of the main application logic.
2. Non-Critical Tasks:
• Daemon threads usually perform non-critical tasks that do not need to complete
before the program exits. Since they are automatically terminated when all user
threads have finished, they are not relied upon for critical application functionality.
7
Creating Thread

• A thread is created either by "creating or implementing" the


Runnable Interface or by extending the Thread class.
• These are the only two ways through which we can create a
thread.

8
Extending the Thread class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
} }
public class Main {
public static void main(String[] args) {

MyThread dd = new MyThread();

dd.start();
} }
9
Implementing the Runnable
interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread dd= new Thread(myRunnable);

dd.start();
} }
10
Creating Multiple Threads
• Creating multiple threads in Java allows your program to
perform multiple tasks concurrently.

11
Creating Multiple Threads

class A extends Thread{ class h {


public void run(){
public static void
for(int i=0;i<10;i++){ main(String[] args) {
System.out.println(i);
A aha = new A();
try{Thread.sleep(1000);}
catch(Exception e){} B bha = new B();
} aha.start();
}} try{Thread.sleep(80);}
catch(Exception e){}
class B extends Thread { bha.start();
public void run(){
}
for (int i=0; i<10; i++){
}
System.out.println("Sheryl");
try{Thread.sleep(1000);}
catch(Exception e){}
}} }
12
Synchronization

• Synchronization in Java is a technique used to control


access to shared resources by multiple threads to prevent
data corruption or inconsistency.
• When multiple threads access shared data concurrently, it
can lead to race conditions, where the outcome of the
program depends on the relative timing of the thread
execution.
• Synchronization ensures that only one thread can access
the shared resource at a time, thereby preventing race
conditions.

13
Without Synchronized
class CounterWithoutSync { Thread thread1 = new
Thread(task);
int count = 0; Thread thread2 = new
public void increment() { Thread(task);
thread1.start();
count++; }
thread2.start();
int getCount() {
return count; } } try {
thread1.join();
class WithoutSyncExample { thread2.join();
} catch (InterruptedException e)
public static void main(String[] {
args) {
CounterWithoutSync counter = new }
CounterWithoutSync();
System.out.println( counter.getCount());
Runnable task = () -> { }
for (int i = 0; i < 1000; i+ }
+) {
14
counter.increment();
With Synchronized
class CounterWithSync { Thread thread1 = new Thread(task);
int count = 0; Thread thread2 = new Thread(task);

synchronized void increment() { thread1.start();


count++; thread2.start();
}
try {
public int getCount() {
thread1.join();
return count;
}} thread2.join();
class WithSyncExample { } catch
public static void main(String[] (InterruptedException e) { }
args) {
CounterWithSync counter = new System.out.println( counter.getCount
CounterWithSync(); ());
Runnable task = () -> { } }
for (int i = 0; i < 1000; i+
+) {
counter.increment(); 15
Suspending Threads

• In Java, suspending threads refers to pausing the


execution of a thread temporarily.
• This can be useful in certain situations where you want
a thread to pause for some time before continuing its
execution.
• One common way to suspend a thread is by using the
Thread.sleep() method, which causes the currently
executing thread to sleep (or pause) for a specified
amount of time.

16
Resuming Threads

• Resuming threads in Java involves allowing a thread that was


previously suspended or paused to continue its execution.
• In Java, the Thread.resume() method used to be available for
this purpose.
• However, it's considered unsafe and deprecated because it can
lead to deadlock situations.
• Instead, a common approach is to use a flag or a mechanism like
wait/notify or synchronization to control the execution of threads
more safely.

17
Stopping Threads

• Stopping threads in Java involves terminating the execution of a


thread.
• Similar to suspending threads, directly stopping threads using the
Thread.stop() method is deprecated and considered unsafe
because it can leave objects in an inconsistent state and potentially
cause deadlocks.
• A safer approach is to use a flag or a mechanism to signal to the
thread that it should stop its execution gracefully.

18

You might also like