Biruk Tewoderos 1790
Biruk Tewoderos 1790
ID DBUR1790/13
COURSECODE COSC3053
Table of Contents
1 What is Thread? 2
3 Process vs thread 5
This content takes a closer look at the concepts of threads, multithreading, multitasking, and multiprocessing. It
also explains the difference between processes and threads, and various techniques used to achieve thread-
based multitasking and multithreading. We'll also look at thread synchronization and priority, and the different
types of synchronization used in Java. It also provides sample code samples demonstrating various types of
thread synchronization and mutual exclusion. Finally, we'll discuss inter-thread communication and how to
implement it using the wait(), notify(), and notifyAll() methods.
What is Thread?
A thread is a single sequential flow of control within a program.
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple
threads of execution running concurrently. Every thread has a priority. Threads with higher priority are executed in
preference to threads with lower priority
independent unit of execution within a program that consists of a set of instructions and its own stack, program
counter, and registers. It represents the smallest unit of processing and allows parallel execution of multiple threads
within a larger program, making better use of system resources and improving application performance.
Threads within a process, share the code, data, and heap sections but have their own stack segments.
Threads share static variables and instance variables of an object.
✦To implement the Runnable interface (by defining run()) and embed class instances in a Thread object.
• Once a Thread instance is created, call the start() method to make it run.
✦ The code following the call to start() will execute concurrently with the thread’s run method.
In Java, a Thread is a lightweight, concurrent unit of execution that consists of a set of instructions. It is a separate
path of execution in a program that runs concurrently with other threads. Java supports multithreading, allowing
multiple threads to run simultaneously, thereby improving the efficiency and performance of a program.
Creating a thread
There are two ways to create a thread.
1 It can be created by extending the Thread class and overriding its run() method:
Running a thread
If your class extends the Thread class, you can run a thread by creating an instance of the class and calling its
start() method.
Then If a class implements the Runnable interface, you can run a thread by passing an instance of the class to the
constructor of a Thread object and then calling the thread's start() method.
Multiprogramming
o "The simultaneous presence of multiple programs in main memory is called multiprogramming."
o Since there are multiple programs in memory, as soon as the currently running program finishes running, the next
one is sent to be used.
o Even if the currently executing program requests I/O resources, another program is submitted to the CPU for
execution in the meantime.
o The main goals of multiprogramming are:
Multithreading
is a technique used for concurrent execution of more than one part of a program, enabling maximum utilization of
CPU. The primary purpose of multithreading is to improve the performance and responsiveness of an application by
running threads in parallel, while also efficiently sharing processor resources and allowing other threads to continue
executing even if one thread is blocked or waiting.
Multitasking is a method of concurrently managing multiple tasks (programs) on a computer by effectively sharing
system resources, such as CPU, memory, and I/O devices. It allows multiple tasks to be executed simultaneously,
switching between them as needed and making the system more responsive and efficient.
o Multiple jobs are executed by the CPU simultaneously by switching between them.
Multiprocessing
is a system that uses multiple processors or multi-core processors to execute multiple tasks or processes
simultaneously. In a multiprocessing system, tasks can be distributed across multiple CPUs, enabling faster execution
and increased overall performance.
o Symmetric multiprocessing: Here the operating system resides on one of her processors and the other runs user
programs.
o Asymmetric Multiprocessing: The operating system runs on any available processor, or all processors run user
programs simultaneously.
o A multiprocessor system can be represented virtually as: 3
Running Running
Running multiple
Running multiple multiple multiple
tasks
Definition programs on a single threads within a processes on
(applications) on
CPU single task multiple CPUs
a single CPU
(application) (or cores)
Resources
Resources (CPU, Each process
Resources (CPU, (CPU,
Resource memory) are has its own set
memory) are shared memory) are
Sharing shared among of resources
among programs shared among
tasks (CPU, memory)
threads
Requires a Requires a
Requires a
Requires a context context switch context switch
Context context switch to
switch to switch to switch to switch
Switching switch between
between programs between between
tasks
threads processes
4
Process vs thread
Process
A Process is inert. A process never executes anything; it is simply a container for threads.
Threads run in the context of a process. Each process has at least one thread.
A thread represents a path of execution that has its own call stack and CPU state.
Threads are confined to context of the process that created them.
– A thread executes code and manipulates data within its process’s address space.
– If two or more threads run in the context of a single process they share a common address
space. They can execute the same code and manipulate the same data.
– Threads sharing a common process can share kernel object handles because the handles
belong to the process, not individual threads.
Properties of process
Here are the important properties of the process:
Creation of each process requires separate system calls for each process.
It is an isolated execution entity and does not share data and information.
Processes use the IPC(Inter-Process Communication) mechanism for communication that
significantly increases the number of system calls.
Process management takes more system calls.
A process has its stack, heap memory with memory, and data map.
what is thread
Threads are a subset of processes, also known as lightweight processes. A process can contain multiple
threads, which are independently managed by the scheduler. All threads within a process are linked together.
Threads share information such as: B. Data segments, code segments, files, etc. shared between peer threads.
However, it contains its own registers, stacks and counters.
Properties of Thread
Here are important properties of Thread:
Thread type
There are two types of threads:
1. User-level threads
As the name suggests, user-level threads are managed only by the user and the kernel has no
knowledge of them.
They are faster and easier to create and manage.
The kernel takes all these threads as her one process and treats them as just her one process.
User-level threads are implemented by user-level libraries, not by system calls
. 2. Kernel-level threads
Kernel-level threads are handled by the operating system and managed by the kernel. These threads are
slower than user-level threads because the context information is managed by the kernel. To create and
implement kernel-level threads, you need to make a system call.
Process
Global Variables
Process Heap
3. It takes more time for creation. It takes less time for creation.
Process switching uses an Thread switching does not require calling an operating
9. interface in an operating system. system and causes an interrupt to the kernel.
13. A system call is involved in it. No system call is involved, it is created using APIs.
S.NO Process Thread
1. Thread-based multitasking:
Thread-based multitasking is a form of multitasking in which a single process has multiple threads of
execution. These threads belong to the same process, share its memory and resources and can run
concurrently, allowing tasks to be done simultaneously. Each thread works independently and executes
instructions in parallel or concurrently.
For example, in a word processor application, one thread can be responsible for spell checking, and
another for formatting the text simultaneously. This enhances the performance of the application since it
divides the tasks among different threads rather than executing them sequentially.
8
2) thread-based multitasking (multithreading)
o Threads share the same address space.
o Threads are lightweight.
o Low communication cost between threads.
Multithreading:.
Multithreading is a technique employed in thread-based multitasking that allows multiple threads to
execute simultaneously within a single process. Multithreading enables a CPU to manage and run
multiple threads without the need to create a new process for each task. This enhances resource
utilization, improves application responsiveness, and reduces the overhead associated with process
creation.
Thread Synchronization:
Programming a multi-threaded process requires great care. The main difficult issues are the sharing
of objects and the techniques used for thread coordination and cooperation.
Each thread’s local variables in methods are private to it – threads have private stacks. However,
threads are not given private copies of static (class) variables or object instance variables.
Thread synchronization is needed to as two threads may try to alter a shared instance or static
variable at the same time.
Java allows threads to be blocked and woken up via arbitrary objects that act as condition variables.
A thread that needs to block awaiting a certain condition calls an object’s wait() method.
Another thread calls notify() to unblock at most one thread or notifyAll() to unblock all threads
waiting on that object.
As an example, when a worker thread discovers that there are no requests to process, it calls wait()
on the instance of Queue. When the I/O thread subsequently adds a request to the queue, it calls
the queue’s notify() method to wake up a worker.
it is a mechanism that ensures that different threads within a process can operate concurrently but in a
controlled manner. It ensures that only one thread can access shared resources (memory or data
structures) at a time, thus preventing race conditions or data corruption.
9
Thread Priorities:
Thread priorities are assigned to the threads by the operating system, precisely the thread scheduler, to
determine the execution order of the threads in a multi-threaded environment. Threads with higher
priorities are prioritized for execution before the threads with lower priorities. However, different
operating systems and schedulers may handle priorities differently.
Thread priorities can be used to manage the responsiveness of an application, ensuring that critical tasks
are completed first or more frequently. For example, a thread handling user input should have a higher
priority than a background thread performing less important tasks.
Keep in mind that setting thread priorities are not a guaranteed way to predict or control the order of
thread execution, as this largely depends on the thread scheduler and the operating system. It is essential
to use appropriate thread synchronization techniques to ensure that important tasks complete in the
desired order.
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be
achieved by using the following three ways:
import java.io.*;
import java.util.*;
class my {
public void my(String yxx)
{
System.out.println( yxx);
try {
Thread.sleep(100);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println( yxx );
}
}
class ThreadedSend extends Thread {
private String yxx;
my my;
Synchronized (my)
{
my.send(yxx);
}
}
}
class we {
public static void main(String args[])
{
my send = new my();
ThreadedSend y1 = new ThreadedSend(" biruk ", send);
ThreadedSend y2 = new ThreadedSend("td ", send);
y1.start();
y2.start();
try {
y1.join();
y2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}}
Output
biruk Sent
td Sent
In many programming languages and libraries, mutual exclusion can be achieved by using locks,
semaphores, or other synchronization primitives. When a thread wants to enter a critical section, it must
first acquire a lock or semaphore. If the lock is already held by another thread, the requesting thread will
have to wait until the lock is released. This way, only one thread can execute the critical section at a time.
class Mutual {
private int counter;
public Mutual (int initialValue) {
this.counter = initialValue;
}
public synchronized void increment() {
counter++;
System.out.println("Incremented: " + counter);
}
public synchronized void decrement() {
counter--;
System.out.println("Decremented: " + counter);
}
}
incrementThread.start();
decrementThread.start();
try {
incrementThread.join();
decrementThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread1 extends Thread{
my t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class Thread2 extends Thread{
my t;
Thread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
TestSynchronization2.java
class my
{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
we.sleep(400);
}catch(Exception e){}
}
}
}
class Thread1 extends we{
public void run(){
my.printTable(1);
}
}
class Thread2 extends we{
public void run(){
my.printTable(10);
}
}
class Thread3 extends we{
public void run(){
my.printTable(100);
}
}
class Thread4 extends we{
public void run() {
my.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
Thread1 t1=new Thread1 ();
Thread2 t2=new Thread2();
Thread3 t3=new Thread3();
Thread4 t4=new Thread4();
t1.start();t2.start();
t3.start();t4.start();
}
}
* wait(), notify() and notifyAll() methods - These methods belong to the Object class and allow threads to
coordinate their actions by signaling each other. A thread can use the wait() method to wait for another thread to finish
its work. Another thread can use notify() to notify that the task has completed and wake up waiting threads.
NoticeAll() can notify multiple waiting threads. This mechanism requires a synchronized block or method to ensure
that only one thread can execute code at a time.
class C{
int am=200;
class Test{
public static void main(String args[]){
final C c=new C();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start(); }}
communication example;
public class my {
we b = new we();
b.start();
synchronized (b) {
System.out.println(" calling wait() method"); // step 1
b.wait();
System.out.println(" notification call"); // step 4
System.out.println("totol balance " + b.totalBalance);
}
class we extends we {
int Balance = 0;
summary
A thread is a single sequential flow of control within a program.
Threads within a process, share the code, data, and heap sections but have their own stack segments.
✦ The code following the call to start() will execute concurrently with the thread’s run method.
It is a separate path of execution in a program that runs concurrently with other threads.
The primary purpose of multithreading is to improve the performance and responsiveness of an
application by running threads in parallel, while also efficiently sharing processor resources and
allowing other threads to continue executing even if one thread is blocked or waiting.
• Processes use the IPC(Inter-Process Communication) mechanism for communication that
significantly increases the number of system calls.
Reference
Java: The Comprehensive Guide to Java Programming for Professionals (Rheinwerk Computing)
Java: The Complete Reference (Osborne Complete Reference Series) 7th Edition
https://www.seas.upenn.edu/~cis110/current/lectures/References.pdf
https://www.simplilearn.com/tutorials/java-tutorial/java-api
https://i.stack.imgur.com/NVNge.jpg
17