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

Multithreading vs. Multitasking in Java

The document discusses the concepts of multithreading and multitasking, highlighting the differences between process-based multitasking and thread-based multitasking. It explains the life cycle of a thread in Java, methods for creating threads, and common concurrency problems. Additionally, it covers thread priority and provides examples of implementing threads in Java.

Uploaded by

ajaysir2k6
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)
9 views10 pages

Multithreading vs. Multitasking in Java

The document discusses the concepts of multithreading and multitasking, highlighting the differences between process-based multitasking and thread-based multitasking. It explains the life cycle of a thread in Java, methods for creating threads, and common concurrency problems. Additionally, it covers thread priority and provides examples of implementing threads in Java.

Uploaded by

ajaysir2k6
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

21CS203 / Object Oriented Programming 2025

UNIT-III
MULTITHREADING AND INPUT/OUTPUT
Multi-threading Vs Multitasking
Multi-Tasking

 Multi-tasking is a process of executing multiple tasks simultaneously.


 We use multitasking to utilize the CPU.
 Multitasking can be achieved in two ways:
1. Process-based Multitasking (Multiprocessing)
2. Thread-based Multitasking (Multithreading)

1. Process-based Multitasking (Multiprocessing)


 Each process has an address in memory. In other words, each process allocates a
separate memory area.
 A process is heavy weight.
 Cost of communication between the processes is high.
 Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2. Thread-based Multitasking (Multithreading)


 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

Examples of thread-based multithreading in Java:

1. A very good example of thread-based multitasking is a word processing program


that checks the spelling of words in a document while writing the document. This
is possible only if each action is performed by a separate thread.
2. Another familiar example is a browser that starts rendering a web page while it is
still downloading the rest of page.

Dr. [Link], CSE, VCET Page 1 of 10


21CS203 / Object Oriented Programming 2025

Difference between Multitasking and Multithreading

Parameters Multi-Tasking Multi-Threading


Basics The process of multi-tasking The process of multi-threading lets
lets a CPU execute various a CPU generates multiple threads
tasks at the very same time. out of a task and processes all of
them simultaneously.
Working A user can easily perform A CPU gets to divide a single
various tasks simultaneously program into various threads so
with their CPU using multi- that it can work more efficiently
tasking. and conveniently. Thus, multi-
threading increases computer
power.
Resources The system needs to allocate The system allocates a single
and Memory separate resources and memory to any given process in
memory to different programs multi-threading. The various
working simultaneously in threads generated out of it share
multi-tasking. that very same resource and
memory that the CPU allocated to
them.
Switching There is the constant The CPU constantly switches
switching between various between the threads and not
programs by the CPU. programs.
Multiprocessing It involves multiprocessing It does not involve multiprocessing
among the various among its various components.
components.
Speed of Executing multi-tasking is Executing multi-threading is
Execution comparatively slower. comparatively much faster.
Process The termination of a process The termination of a process
Termination takes up comparatively more takes up comparatively less time
time in multi-tasking. in multithreading.

What is Thread in Java

 A thread is a lightweight sub-process, the smallest unit of processing.


 It is a separate path of execution. Threads are independent.
 When main method is called JVM will gives a thread (at least one thread) called main
thread.
 If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
Dr. [Link], CSE, VCET Page 2 of 10
21CS203 / Object Oriented Programming 2025

 As shown in the figure, a thread is executed inside the process.


 There is context-switching between the threads.
 There can be multiple processes inside the OS, and one process can have multiple
threads.

Life Cycle and State Transition diagram of a java thread

Dr. [Link], CSE, VCET Page 3 of 10


21CS203 / Object Oriented Programming 2025

Life Cycle State Transition

1. New: In this phase, the thread is created using class “Thread class”. It remains in this
state till the program starts the thread. It is also known as born thread.
2. Runnable: In this phase, the instance of the thread is invoked with a start method.
The thread control is given to scheduler to finish the execution. It depends on the
scheduler, whether to run the thread.
3. Running: When the thread starts executing, then the state is changed to “running”
state. The scheduler selects one thread from the thread pool, and it starts executing in
the application.
4. Waiting: This is the state when a thread has to wait. As there multiple threads are
running in the application, there is a need for synchronization between threads. Hence,
one thread has to wait, till the other thread gets executed. Therefore, this state is
referred as waiting state.
5. Dead: This is the state when the thread is terminated. The thread is in running state
and as soon as it completed processing it is in “dead state”.

Dr. [Link], CSE, VCET Page 4 of 10


21CS203 / Object Oriented Programming 2025

HOW TO CREATE THREAD IN JAVA


Threads can be made in two different ways:

1. Extending the Thread class


2. Implementing the Runnable Interface
1. Extending the Thread class
 The first approach is to make a class that extends Thread ([Link]).
 The run() method of the Thread class is overridden by this class. This method serves as
the thread's entry point, and it's where we'll place our simple logic.
 Syntax of run() method: public void run()
 Then, to begin thread execution, we define an object of our new class and use the start()
method.
 Syntax of start() method: void start( );
 The start() method on the Thread object calls the run() method.

Example 1: Creating single thread


If the class extends the Thread class, the thread can be run by creating an instance of the
class and call its start() method:
1. class ThreadTest extends Thread // Create the extended class
2. {
3. public void run() // Override the run method
4. {
a. [Link]( "thread created successfully by extended thread class" );
5. }
6. public static void main(String args[])
7. {
a. ThreadTest trd_obj = new ThreadTest(); // Create the thread
b. trd_obj.start(); // Run the threads
8. }
9. }

Dr. [Link], CSE, VCET Page 5 of 10


21CS203 / Object Oriented Programming 2025

2. Implementing the Runnable Interface


 The second step involves creating a new class that implements the Runnable interface
([Link] interface) and overriding the run() method.
 Then we create a Thread object and call its start() method.
 If the class implements the Runnable interface, the thread can be run by passing an
instance of the class to a Thread object's constructor and then calling the
thread's start() method:

Example 1: Creating single thread


1. public class Main implements Runnable
2. {
3. public static void main(String[] args)
4. {
5. Main obj = new Main(); // The thread is created
6. Thread thread = new Thread(obj);
7. [Link](); // The thread is Runnable
8. [Link]("This code is outside of the thread");
9. }
10. public void run()
11. {
12. [Link]("This code is running in a thread");
13. }
14. }

Differences between "extending" and "implementing" Threads

 When a class extends the Thread class, you cannot extend any other class.
 By implementing the Runnable interface, it is possible to extend from another class as
well, like: class MyClass extends OtherClass implements Runnable.

Dr. [Link], CSE, VCET Page 6 of 10


21CS203 / Object Oriented Programming 2025

Concurrency Problems

 When threads run at the same time, the order of the code running is not known.
 When the threads and main program are reading and writing the same variables, the
values are unpredictable - called concurrency problem.
 To avoid concurrency problems, it is best to share as few attributes between threads as
using isAlive() method - thread has finished running before using any attributes.
Example : Concurrency Problem
1. public class Main extends Thread 1. public class Main extends Thread
2. { 2. {
3. public static int amount = 0; 3. public static int amount = 0;
4. public static void main(String[]args) 4. public static void main(String[]args)
5. { 5. {
6. Main thread = new Main(); 6. Main thread = new Main();
7. [Link](); 7. [Link]();
8. [Link](“initial value” + 8. // Wait for the thread to finish
amount); 9. while([Link]())
9. amount++; 10. {
10. [Link](“incremented 11. [Link]("Waiting...");
thread” +amount); 12. }
11. } 13. // Update amount & print its value
12. public void run() 14. [Link]("Main:"+amount);
13. { 15. amount++;
14. amount++; 16. [Link]("Main:"+amount);
15. } 17. }
16. } 18. public void run()
19. {
20. amount++;
21. }
22. }

Output: Output:
Waiting...
Initial value:0
Main: 1
Incremented value:2
Main: 2

Dr. [Link], CSE, VCET Page 7 of 10


21CS203 / Object Oriented Programming 2025

Commonly used methods for threads

Method Description
start() This method starts the execution of the thread and JVM calls
the run() method on the thread.
Sleep(int milliseconds) This method makes the thread sleep hence the thread’s
execution will pause for milliseconds provided and after that,
again the thread starts executing. This help in
synchronization of the threads.

getName() It returns the name of the thread.

setPriority(int newpriority) It changes the priority of the thread.

yield () It causes current thread on halt and other threads to execute.

 A java thread comes with a pre-assigned priority.


 In addition to this, the java virtual machine can also assign priority to threads or
explicitly given by the programmers.
 The range of values for the priority of a thread lies between 1 and 10 (inclusive).
 The three static variables associated with priority are −
o MAX_PRIORITY − The max priority that a thread has, whose default value is 10.
o NORM_PRIORITY − The default priority that a thread has, whose default value is 5.
o MIN_PRIORITY − The minimum priority that a thread has, whose default value is 1

Example : Creating multiple threads with priority

1. // Importing the required classes


2. import [Link].*;

3. public class ThreadPriorityExample extends Thread


4. {

5. // Method 1: Whenever the start() is called by a thread the run() method is invoked
6. public void run()

7. {
8. [Link]("Inside the run() method");

Dr. [Link], CSE, VCET Page 8 of 10


21CS203 / Object Oriented Programming 2025

9. }

10. // the main method


11. public static void main(String argvs[])

12. {
13. ThreadPriorityExample th1 = new ThreadPriorityExample();

14. ThreadPriorityExample th2 = new ThreadPriorityExample();


15. ThreadPriorityExample th3 = new ThreadPriorityExample();

16. // The priorities of the thread is 5, the default value


17. // Displaying the priority of the thread using the getPriority() method

18. [Link]("Priority of the thread th1 is : " + [Link]());


19. [Link]("Priority of the thread th2 is : " + [Link]());

20. [Link]("Priority of the thread th2 is : " + [Link]());


21. // Setting priorities of above threads by passing integer arguments

22. [Link](6);
23. [Link](3);

24. [Link](9);
25. [Link]("Priority of the thread th1 is : " + [Link]());

26. [Link]("Priority of the thread th2 is : " + [Link]());


27. [Link]("Priority of the thread th3 is : " + [Link]());

28. // Main thread Displaying name of the currently executing thread


29. // No thread is started, only the main thread is running

30. [Link]("Currently Executing The Thread : "+[Link]().getName());


31. [Link]("Priority of the main thread is : " + [Link]().getPriority());

32. // Priority of the main thread is 10 now


33. [Link]().setPriority(10);

34. [Link]("Priority of the main thread is : " + [Link]().getPriority());


35. }

36. }

Dr. [Link], CSE, VCET Page 9 of 10


21CS203 / Object Oriented Programming 2025

Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

References:

1. [Link]
2. [Link]
3. [Link]
4. [Link]

******************

Dr. [Link], CSE, VCET Page 10 of 10

You might also like