0% found this document useful (0 votes)
6 views10 pages

33 Multithreding

This document provides an overview of multithreading and concurrency in Java, covering key concepts such as the Thread Class, Runnable Interface, Thread Lifecycle, Synchronization, Executors Framework, and Concurrent Collections. It discusses the advantages and disadvantages of each component, their use cases, and includes example programs to illustrate their implementation. The document emphasizes the importance of multithreading for performance improvement and resource utilization in various applications.

Uploaded by

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

33 Multithreding

This document provides an overview of multithreading and concurrency in Java, covering key concepts such as the Thread Class, Runnable Interface, Thread Lifecycle, Synchronization, Executors Framework, and Concurrent Collections. It discusses the advantages and disadvantages of each component, their use cases, and includes example programs to illustrate their implementation. The document emphasizes the importance of multithreading for performance improvement and resource utilization in various applications.

Uploaded by

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

Multithreading and Concurrency in Java

Contents
1 Introduction 3

2 Thread Class and Runnable Interface 3


2.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Key Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Why Use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.4 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.5 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.6 Where Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3 Thread Lifecycle 4
3.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.2 Why Use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.3 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.4 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.5 Where Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

4 Synchronization and Locks 4


4.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.3 Why Use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.4 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.5 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.6 Where Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

5 Executors Framework 5
5.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.2 Key Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.3 Why Use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.4 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.5 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.6 Where Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

6 Concurrent Collections 6
6.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6.2 Why Use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6.3 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1
6.4 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6.5 Where Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

7 Why Use Multithreading and Concurrency? 7

8 Example Programs 7
8.1 Program 1: Simple Multithreading . . . . . . . . . . . . . . . . . . . . . 7
8.2 Program 2: User-Input with Concurrent Collections . . . . . . . . . . . . 8

9 Conclusion 9

2
1 Introduction
Multithreading and concurrency in Java enable programs to perform multiple tasks si-
multaneously, leveraging multiple CPU cores, improving performance, and enhancing
responsiveness. This document covers the Thread Class and Runnable Interface, Thread
Lifecycle, Synchronization and Locks, Executors Framework, and Concurrent Collections,
with theory, advantages, disadvantages, use cases, and example programs.

2 Thread Class and Runnable Interface


2.1 Theory
The Thread class in the java.lang package allows creating and managing threads. A
thread is a lightweight process for concurrent task execution. By extending Thread and
overriding its run() method, you define the task a thread performs.
The Runnable interface, also in java.lang, provides an alternative for thread cre-
ation. It declares a single run() method. A class implementing Runnable can be passed
to a Thread object for execution.

2.2 Key Differences


• Thread Class: Involves inheritance, limiting flexibility due to Java’s single inher-
itance.

• Runnable Interface: Preferred for modularity, allowing a class to extend another


class or implement multiple interfaces.

2.3 Why Use?


• Thread Class: Used for direct thread customization (e.g., setting names or prior-
ities).

• Runnable Interface: Used for reusable, modular task definitions in complex ap-
plications.

2.4 Advantages
• Thread Class: Simple for basic tasks; direct access to thread methods.

• Runnable Interface: Promotes loose coupling and reusability.

2.5 Disadvantages
• Thread Class: Limits extensibility; less reusable.

• Runnable Interface: Requires additional code to create a Thread object.

2.6 Where Used?


• Thread Class: Simple applications needing thread-specific customization.

• Runnable Interface: Server applications, task scheduling, or reusable tasks.

3
3 Thread Lifecycle
3.1 Theory
A thread in Java transitions through the following states:

1. New: Thread created but not started (new Thread()).

2. Runnable: Thread ready to run after start(); either running or waiting for CPU.

3. Blocked: Waiting to acquire a monitor lock (e.g., in a synchronized block).

4. Waiting: Waiting indefinitely for another thread (e.g., wait(), join()).

5. Timed Waiting: Waiting for a specified time (e.g., sleep(), wait(timeout)).

6. Terminated: Thread completed or stopped.

3.2 Why Use?


Understanding the lifecycle aids in managing threads, debugging issues (e.g., deadlocks),
and controlling behavior (e.g., pausing with sleep()).

3.3 Advantages
• Precise control over thread execution.

• Efficient resource management.

3.4 Disadvantages
• Manual lifecycle management can lead to errors.

• Complex debugging in concurrent systems.

3.5 Where Used?


Thread coordination in producer-consumer problems, GUI applications, or server request
handling.

4 Synchronization and Locks


4.1 Theory
Synchronization ensures only one thread accesses a critical section, preventing race
conditions. Achieved using the synchronized keyword or explicit locks.
The java.util.concurrent.locks package provides ReentrantLock for advanced
locking, supporting fairness, interruptible locks, and condition variables.

4
4.2 Key Concepts
• Synchronized Keyword: Locks a block or method using an object’s monitor.

• ReentrantLock: Offers flexibility (e.g., tryLock(), fairness).

• Race Condition: Inconsistent results from concurrent access to shared resources.

• Deadlock: Threads stuck waiting for each others resources.

4.3 Why Use?


Ensures thread safety for shared resources, preventing data corruption.

4.4 Advantages
• Synchronized: Simple for basic thread safety.

• Locks: Fine-grained control for complex scenarios.

4.5 Disadvantages
• Synchronized: Performance bottlenecks; limited flexibility.

• Locks: Complex; requires manual unlocking.

4.6 Where Used?


• Synchronized: Simple shared resource access (e.g., shared lists).

• Locks: High-performance systems (e.g., banking, concurrent data structures).

5 Executors Framework
5.1 Theory
The java.util.concurrent packages Executors framework simplifies thread manage-
ment with thread pools. ExecutorService manages thread execution, reducing thread
creation overhead.

5.2 Key Components


• ExecutorService: Manages thread pools (e.g., newFixedThreadPool).

• Thread Pools: Reuse threads for efficiency.

• Callable and Future: Callable returns results; Future holds them.

5.3 Why Use?


Simplifies thread management and improves performance via thread reuse.

5
5.4 Advantages
• Reduces thread creation overhead.

• Supports task scheduling and result retrieval.

5.5 Disadvantages
• Poor pool configuration can cause delays or resource exhaustion.

• More complex than raw threads for simple tasks.

5.6 Where Used?


Web servers, parallel processing, and background tasks.

6 Concurrent Collections
6.1 Theory
Concurrent collections in java.util.concurrent are thread-safe data structures. Ex-
amples include:

• ConcurrentHashMap: Thread-safe map for concurrent reads/writes.

• CopyOnWriteArrayList: Thread-safe list for read-heavy scenarios.

• BlockingQueue: Queue for producer-consumer patterns.

6.2 Why Use?


Provides thread-safe collections optimized for concurrency.

6.3 Advantages
• Thread-safe without manual synchronization.

• High performance for concurrent access.

6.4 Disadvantages
• Higher memory usage (e.g., CopyOnWriteArrayList).

• Limited suitability for some scenarios.

6.5 Where Used?


• ConcurrentHashMap: Web servers, caches.

• CopyOnWriteArrayList: Event listeners, read-heavy scenarios.

• BlockingQueue: Producer-consumer problems.

6
7 Why Use Multithreading and Concurrency?
• Purpose: Improves performance, utilizes CPU cores, enhances responsiveness.

• Applications: Web servers, databases, GUIs, parallel computing.

• Benefits: Faster execution, better resource utilization.

• Challenges: Complexity, debugging, performance overhead.

8 Example Programs
8.1 Program 1: Simple Multithreading
This program demonstrates the Thread class, Runnable interface, synchronization, and
Executors.
1 import java . util . concurrent . ExecutorService ;
2 import java . util . concurrent . Executors ;
3

4 // Runnable implementation
5 class MyTask implements Runnable {
6 private String name ;
7 private static int sharedCounter = 0; // Shared resource
8 private final Object lock = new Object () ;
9

10 public MyTask ( String name ) {


11 this . name = name ;
12 }
13

14 @Override
15 public void run () {
16 for ( int i = 0; i < 3; i ++) {
17 synchronized ( lock ) { // Synchronization to avoid
race condition
18 sharedCounter ++;
19 System . out . println ( name + " incremented
counter to : " + sharedCounter ) ;
20 }
21 try {
22 Thread . sleep (100) ; // Simulate work
23 } catch ( I n t e r r u p t e d E xc e p t i o n e ) {
24 e . printStackTrace () ;
25 }
26 }
27 }
28 }
29

30 // Thread class implementation


31 class MyThread extends Thread {
32 public MyThread ( String name ) {
33 super ( name ) ;

7
34 }
35

36 @Override
37 public void run () {
38 for ( int i = 0; i < 3; i ++) {
39 System . out . println ( getName () + " is running , count
: " + i);
40 try {
41 Thread . sleep (100) ;
42 } catch ( I n t e r r u p t e d E xc e p t i o n e ) {
43 e . printStackTrace () ;
44 }
45 }
46 }
47 }
48

49 public class Sim p l e M u l t i t h r e a d i n g {


50 public static void main ( String [] args ) {
51 // Using Thread class
52 MyThread thread1 = new MyThread ( " Thread -1 " ) ;
53 MyThread thread2 = new MyThread ( " Thread -2 " ) ;
54 thread1 . start () ;
55 thread2 . start () ;
56

57 // Using Runnable with ExecutorService


58 ExecutorService executor = Executors .
new Fi xe dT hr ea dP oo l (2) ;
59 executor . submit ( new MyTask ( " Runnable -1 " ) ) ;
60 executor . submit ( new MyTask ( " Runnable -2 " ) ) ;
61

62 // Shutdown executor
63 executor . shutdown () ;
64 }
65 }

8.2 Program 2: User-Input with Concurrent Collections


This program uses ConcurrentHashMap and Executors to process user-input key-value
pairs concurrently.
1 import java . util . Scanner ;
2 import java . util . concurrent . Conc urrent HashMa p ;
3 import java . util . concurrent . ExecutorService ;
4 import java . util . concurrent . Executors ;
5

6 public class Use r I n p u t C o n c u r r e n c y {


7 public static void main ( String [] args ) {
8 Scanner scanner = new Scanner ( System . in ) ;
9 ConcurrentHashMap < String , String > map = new
ConcurrentHashMap < >() ;

8
10 ExecutorService executor = Executors .
new Fi xe dT hr ea dP oo l (2) ;
11

12 // User input for key - value pairs


13 System . out . println ( " Enter number of key - value pairs to
add : " ) ;
14 int n = scanner . nextInt () ;
15 scanner . nextLine () ; // Consume newline
16

17 System . out . println ( " Enter " + n + " key - value pairs ( e
. g . , name value ) : " ) ;
18 for ( int i = 0; i < n ; i ++) {
19 String [] input = scanner . nextLine () . split ( " " ) ;
20 if ( input . length == 2) {
21 map . put ( input [0] , input [1]) ;
22 }
23 }
24

25 // Task to process Concur rentHa shMap entries


concurrently
26 Runnable printTask = () -> {
27 for ( String key : map . keySet () ) {
28 System . out . println ( Thread . currentThread () .
getName () + " processing : " + key + " -> "
+ map . get ( key ) ) ;
29 try {
30 Thread . sleep (100) ; // Simulate processing
31 } catch ( I n t e r r u p te d E x c e p t i o n e ) {
32 e . printStackTrace () ;
33 }
34 }
35 };
36

37 // Submit tasks to ExecutorService


38 executor . submit ( printTask ) ;
39 executor . submit ( printTask ) ;
40

41 // Shutdown executor and close scanner


42 executor . shutdown () ;
43 scanner . close () ;
44 }
45 }

9 Conclusion
Multithreading and concurrency in Java enable efficient, responsive applications. The
Thread class and Runnable interface provide ways to create threads, while synchroniza-
tion and locks ensure thread safety. The Executors framework and concurrent collections
simplify thread management and data sharing, making them essential for modern appli-
cations like web servers, GUIs, and parallel processing systems.

9
lmodern

10

You might also like