0% found this document useful (0 votes)
10 views8 pages

Java Unit 4

This document covers multithreading and collections in Java, detailing the core concepts of multithreading, including thread life cycle, creation, synchronization, and inter-thread communication. It also introduces the Collections Framework, explaining various interfaces such as ArrayList, Vector, HashSet, and TreeSet, along with their important methods and code implementations. The content is structured into topics and subtopics, providing a comprehensive overview of these programming concepts.

Uploaded by

mudassir110701
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)
10 views8 pages

Java Unit 4

This document covers multithreading and collections in Java, detailing the core concepts of multithreading, including thread life cycle, creation, synchronization, and inter-thread communication. It also introduces the Collections Framework, explaining various interfaces such as ArrayList, Vector, HashSet, and TreeSet, along with their important methods and code implementations. The content is structured into topics and subtopics, providing a comprehensive overview of these programming concepts.

Uploaded by

mudassir110701
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

UNIT IV: MULTITHREADING &

COLLECTIONS
Detailed Notes

Contents
1 TOPIC 1: MULTITHREADING 3
1.1 1. Introduction & Core Concept . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Why do we need Multithreading? . . . . . . . . . . . . . . . . . . 3
1.1.2 Real-World Analogy: “The Kitchen” . . . . . . . . . . . . . . . . 3
1.2 2. The Thread Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 3. Creating Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.1 Method A: Extending the Thread Class . . . . . . . . . . . . . . . 3
1.3.2 Method B: Implementing Runnable Interface (Preferred) . . . . . 4
1.4 4. Key Thread Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 5. Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.1 Code Example: Synchronization . . . . . . . . . . . . . . . . . . . 4
1.6 6. Inter-Thread Communication . . . . . . . . . . . . . . . . . . . . . . . 4

2 TOPIC 2: COLLECTIONS FRAMEWORK 5


2.1 1. ArrayList (Interface: List) . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.2 B. Important Methods . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.3 C. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 2. Vector (Interface: List) . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.2 B. Important Methods . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.3 C. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 3. HashSet (Interface: Set) . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.2 B. Important Methods . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.3 C. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 4. TreeSet (Interface: Set) . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4.2 B. Important Methods . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4.3 C. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 7
2.5 5. HashMap (Interface: Map) . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5.2 B. Important Methods . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5.3 C. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 7
2.6 6. Hashtable (Interface: Map) . . . . . . . . . . . . . . . . . . . . . . . . 8

1
2.6.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.6.2 B. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 8
2.7 7. Iterator (Interface) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.7.1 A. Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.7.2 B. Important Methods . . . . . . . . . . . . . . . . . . . . . . . . 8
2.7.3 C. Code Implementation . . . . . . . . . . . . . . . . . . . . . . . 8

2
1 TOPIC 1: MULTITHREADING
1.1 1. Introduction & Core Concept
Multithreading is a Java feature that allows concurrent execution of two or more parts
of a program for maximum utilization of the CPU. Each part of such a program is called
a Thread.

1.1.1 Why do we need Multithreading?


1. Better CPU Utilization: Allows the CPU to do other work (like updating the
UI) while waiting for I/O operations.

2. Responsiveness: Ensures applications (like games or servers) remain responsive


to user input even while performing heavy tasks in the background.

1.1.2 Real-World Analogy: “The Kitchen”


• Single-threading: A Chef chops onions → stops → boils water → stops → makes
sauce.

• Multithreading: The Chef puts water to boil (Thread 1), and while it boils, he
chops onions (Thread 2).

1.2 2. The Thread Life Cycle


A thread goes through 5 distinct states:

1. New: Created (‘new Thread()‘) but not yet started.

2. Runnable: Ready to run, waiting for CPU time.

3. Running: The CPU is executing the thread.

4. Blocked/Waiting: Waiting for I/O or another thread.

5. Terminated: Finished execution.

1.3 3. Creating Threads


1.3.1 Method A: Extending the Thread Class

1 class MyThread extends Thread {


2 public void run () {
3 System . out . println ( " Thread Running " ) ;
4 }
5 }
6 // Usage : MyThread t1 = new MyThread () ; t1 . start () ;

3
1.3.2 Method B: Implementing Runnable Interface (Preferred)

1 class MyTask implements Runnable {


2 public void run () {
3 System . out . println ( " Task Running " ) ;
4 }
5 }
6 // Usage : Thread t1 = new Thread ( new MyTask () ) ; t1 . start () ;

1.4 4. Key Thread Methods


• isAlive(): Checks if thread is still running.

• join(): Waits for a thread to die before proceeding.

• setPriority(int): Sets priority (Min: 1, Norm: 5, Max: 10).

1.5 5. Synchronization
Definition: The capability to control the access of multiple threads to any shared re-
source to prevent data corruption (Race Conditions).

1.5.1 Code Example: Synchronization

1 class Table {
2 // synchronized ensures only one thread enters at a time
3 synchronized void printTable ( int n ) {
4 for ( int i =1; i <=5; i ++) {
5 System . out . println ( n * i ) ;
6 try { Thread . sleep (400) ; } catch ( Exception e ) {}
7 }
8 }
9 }

1.6 6. Inter-Thread Communication


Threads communicate using these methods (must be in synchronized block):

• wait(): Thread releases lock and waits.

• notify(): Wakes up one waiting thread.

• notifyAll(): Wakes up all waiting threads.

4
2 TOPIC 2: COLLECTIONS FRAMEWORK
The Collection Framework provides a standard architecture for storing and manipu-
lating groups of objects.

2.1 1. ArrayList (Interface: List)


2.1.1 A. Explanation
ArrayList is a dynamic array implementation of the List interface. It grows automati-
cally when elements are added. It maintains insertion order and allows duplicates.

2.1.2 B. Important Methods

Method Description
add(E e) Appends element to end.
add(int index, E e) Inserts element at specific index.
get(int index) Returns element at position.
set(int index, E e) Replaces element at position.
remove(int index) Removes element at position.

2.1.3 C. Code Implementation

1 import java . util .*;


2 public class ArrayListDemo {
3 public static void main ( String args []) {
4 ArrayList < String > list = new ArrayList < >() ;
5 list . add ( " Java " ) ;
6 list . add ( " Python " ) ;
7 list . add (1 , " C ++ " ) ; // Insert at index 1
8
9 System . out . println ( " Element at 1: " + list . get (1) ) ;
10 list . remove ( " Python " ) ;
11
12 for ( String s : list ) System . out . println ( s ) ;
13 }
14 }

2.2 2. Vector (Interface: List)


2.2.1 A. Explanation
Vector is similar to ArrayList but is Synchronized (Thread-safe). This makes it safer
for multithreading but slower in performance. It is considered a legacy class.

2.2.2 B. Important Methods


Contains all List methods plus legacy methods like addElement().

5
2.2.3 C. Code Implementation

1 import java . util .*;


2 public class VectorDemo {
3 public static void main ( String args []) {
4 Vector < String > v = new Vector < >() ;
5 v . add ( " Apple " ) ;
6 v . addElement ( " Banana " ) ; // Legacy method
7
8 System . out . println ( " Capacity : " + v . capacity () ) ;
9 System . out . println ( " Elements : " + v ) ;
10 }
11 }

2.3 3. HashSet (Interface: Set)


2.3.1 A. Explanation
HashSet implements the Set interface using a hash table. It does not allow duplicate
elements and does not guarantee any specific order of elements.

2.3.2 B. Important Methods

Method Description
add(E e) Adds element if not present (returns false if dupli-
cate).
contains(Object o) Returns true if set contains the element.
remove(Object o) Removes the specified element.

2.3.3 C. Code Implementation

1 import java . util .*;


2 public class HashSetDemo {
3 public static void main ( String args []) {
4 HashSet < String > set = new HashSet < >() ;
5 set . add ( " One " ) ;
6 set . add ( " Two " ) ;
7 set . add ( " One " ) ; // Duplicate ignored
8
9 System . out . println ( " Set contains One ? " + set . contains ( " One " ) ) ;
10 System . out . println ( " Set : " + set ) ; // Order is unpredictable
11 }
12 }

2.4 4. TreeSet (Interface: Set)


2.4.1 A. Explanation
TreeSet implements the Set interface using a Tree structure. It ensures Sorted Order
(ascending by default). Like HashSet, it does not allow duplicates.

6
2.4.2 B. Important Methods

Method Description
first() Returns the first (lowest) element.
last() Returns the last (highest) element.
headSet(E toElement) Returns elements less than toElement.

2.4.3 C. Code Implementation

1 import java . util .*;


2 public class TreeSetDemo {
3 public static void main ( String args []) {
4 TreeSet < Integer > ts = new TreeSet < >() ;
5 ts . add (50) ;
6 ts . add (10) ;
7 ts . add (30) ;
8
9 System . out . println ( " Sorted : " + ts ) ; // [10 , 30 , 50]
10 System . out . println ( " Highest : " + ts . last () ) ;
11 }
12 }

2.5 5. HashMap (Interface: Map)


2.5.1 A. Explanation
HashMap stores data in Key-Value pairs. Keys must be unique, but values can be
duplicated. It allows one null key. It is not synchronized.

2.5.2 B. Important Methods

Method Description
put(K key, V value) Inserts mapping. Overrides if key exists.
get(Object key) Returns value associated with key.
containsKey(Object k) Checks existence of key.
entrySet() Returns Set view for iteration.

2.5.3 C. Code Implementation

1 import java . util .*;


2 public class HashMapDemo {
3 public static void main ( String args []) {
4 HashMap < Integer , String > map = new HashMap < >() ;
5 map . put (101 , " Amit " ) ;
6 map . put (102 , " Ravi " ) ;
7 map . put (101 , " Vijay " ) ; // Replaces Amit
8
9 for ( Map . Entry m : map . entrySet () ) {
10 System . out . println ( m . getKey () + " " + m . getValue () ) ;
11 }
12 }
13 }

7
2.6 6. Hashtable (Interface: Map)
2.6.1 A. Explanation
Hashtable is the legacy version of HashMap. It is Synchronized (thread-safe) and does
not allow any null keys or null values.

2.6.2 B. Code Implementation

1 import java . util .*;


2 public class HashtableDemo {
3 public static void main ( String args []) {
4 Hashtable < Integer , String > table = new Hashtable < >() ;
5 table . put (1 , " A " ) ;
6 table . put (2 , " B " ) ;
7 // table . put ( null , " C ") ; // Throws N u l l P o i n t e r E x c e p t i o n
8 System . out . println ( table ) ;
9 }
10 }

2.7 7. Iterator (Interface)


2.7.1 A. Explanation
Iterator is a universal cursor used to traverse any Collection (List, Set, Queue). It
allows safe removal of elements during iteration.

2.7.2 B. Important Methods


• hasNext(): Returns true if more elements exist.

• next(): Returns the next element.

• remove(): Removes the last element returned.

2.7.3 C. Code Implementation

1 import java . util .*;


2 public class IteratorDemo {
3 public static void main ( String args []) {
4 ArrayList < String > list = new ArrayList < >() ;
5 list . add ( " A " ) ; list . add ( " B " ) ; list . add ( " C " ) ;
6
7 Iterator < String > it = list . iterator () ;
8 while ( it . hasNext () ) {
9 String s = it . next () ;
10 if ( s . equals ( " B " ) ) it . remove () ; // Safely remove
11 }
12 System . out . println ( list ) ; // [A , C ]
13 }
14 }

You might also like