Multithreading 2.3.1
Multithreading 2.3.1
2
• Benefits of Using Threads
• Concurrency: Allows multiple operations to run simultaneously.
• Resource Sharing: Threads within the same process can share resources,
reducing overhead.
• Responsive Applications: Enhances responsiveness, especially in GUI-based
applications.
• Parallel Processing: Makes use of multi-core processors to execute tasks in
parallel.
3
Basic Thread Lifecycle
• New: A thread object is created but not yet started.
• Runnable: The thread is ready to run and waiting for CPU time.
• Running: The thread is executing its task.
• Blocked/Waiting: The thread is paused and waiting for resources.
• Terminated: The thread has completed its execution.
4
Code Example
public class ThreadExample extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
ThreadExample thread = new ThreadExample();
thread.start(); // Start the thread
}
}
5
The Main Thread
In every Java program, the main thread is the first thread to execute. It is created automatically
when the program starts and serves as the entry point for all other threads.
6
Managing the Main Thread
Java provides methods to control the main thread using the Thread class. For example, you can change the thread's
name, priority, or state.
Code Example
public class MainThreadExample {
public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
System.out.println("Main thread name: " + mainThread.getName());
10
Thread Priority
Threads can have priorities ranging from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with a default value of 5
(NORM_PRIORITY). Higher-priority threads are more likely to execute before lower-priority ones.
Code Example
public class ThreadPriorityExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> System.out.println("Thread 1 running..."));
Thread thread2 = new Thread(() -> System.out.println("Thread 2 running..."));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
}}
11
Thread Synchronization
Thread synchronization prevents multiple threads from accessing shared resources simultaneously, ensuring data
consistency.
Synchronized Method
class SharedResource {
synchronized void printNumbers() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}}}}
12
public class SynchronizationExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
t1.start();
t2.start();
}
}
13
THANK YOU
14