0% found this document useful (0 votes)
7 views

Multithreading

Multithreading allows multiple threads to execute within the same memory space, enabling applications to perform distinct tasks independently and maintain responsiveness. Java supports multithreading through the Runnable interface and by extending the Thread class, with built-in synchronization and scheduling features. Applications such as GUIs and network-based systems benefit significantly from multithreading, as it allows for asynchronous processing and efficient resource utilization.

Uploaded by

anshumanatm
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)
7 views

Multithreading

Multithreading allows multiple threads to execute within the same memory space, enabling applications to perform distinct tasks independently and maintain responsiveness. Java supports multithreading through the Runnable interface and by extending the Thread class, with built-in synchronization and scheduling features. Applications such as GUIs and network-based systems benefit significantly from multithreading, as it allows for asynchronous processing and efficient resource utilization.

Uploaded by

anshumanatm
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/ 5

What is Multithreading?

Multithreading is similar to multi-processing.

A multi-processing Operating System can run several processes at the


same time
Each process has its own address/memory space
The OS's scheduler decides when each process is executed
Multithreading in Java Only one process is actually executing at any given time. However, the
system appears to be running several programs simultaneously

Separate processes to not have access to each other's memory space


Many OSes have a shared memory system so that processes can share
memory space

• In a multithreaded application, there are several points of execution within


the same memory space.
• Each point of execution is called a thread
• Threads share access to memory

Why use Multithreading? What Kind of Applications Use Multithreading?


In a single threaded application, one thread of execution must do everything Any kind of application which has distinct tasks which can be performed
If an application has several tasks to perform, those tasks will be independently
performed when the thread can get to them. Any application with a GUI.
A single task which requires a lot of processing can make the entire Threads dedicated to the GUI can delegate the processing of user
application appear to be "sluggish" or unresponsive. requests to other threads.
The GUI remains responsive to the user even when the user's requests
• In a multithreaded application, each task can be performed by a separate
are being processed
thread
Any application which requires asynchronous response
If one thread is executing a long process, it does not make the entire
Network based applications are ideally suited to multithreading.
application wait for it to finish.
Data can arrive from the network at any time.
• If a multithreaded application is being executed on a system that has In a single threaded system, data is queued until the thread can read
multiple processors, the OS may execute separate threads simultaneously the data
on separate processors. In a multithreaded system, a thread can be dedicated to listening for
data on the network port
When data arrives, the thread reads it immediately and processes it
or delegates its processing to another thread

A single threaded program A Multithreaded Program


class ABC
{ Main Thread

….
public void main(..) begin start
start start
{
… body

..
end Thread A Thread B Thread C
}
}
Threads may switch or exchange data/results
5 6

1
How does it all work?
Each thread is given its own "context"
Java Threads
A thread's context includes virtual registers and its own calling stack

• The "scheduler" decides which thread executes at any given time • Java has built in thread support for Multithreading
The VM may use its own scheduler • Synchronization
Since many OSes now directly support multithreading, the VM may use
the system's scheduler for scheduling threads • Thread Scheduling
• The scheduler maintains a list of ready threads (the run queue) and a list of • Inter-Thread Communication:
threads waiting for input (the wait queue)
– currentThread start setPriority
Each thread has a priority. The scheduler typically schedules between the – yield run getPriority
highest priority threads in the run queue
Note: the programmer cannot make assumptions about how threads are – sleep stop suspend
going to be scheduled. Typically, threads will be executed differently on – resume
different platforms.
• Java Garbage Collector is a low-priority thread

java.lang.Thread
• Two techniques to create threads in java
• 1) implementing the Runnable interface
An example
– The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread. The class must define a method,
called run, with no arguments. class MyThread extends Thread { // the thread
– invoke Thread constructor with an instance of this Runnable class public void run() {
• 2) extending Thread System.out.println(" this thread is running ... ");
– Define a subclass of java.lang.Thread }
• Define a run method } // end class MyThread
– In another thread (e.g., the main), create an instance of the Thread subclass
• Then, call start method of that instance class ThreadEx1 { // a program that utilizes the thread
public static void main(String [] args ) {
MyThread t = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
t.start();
} // end main()
} // end class ThreadEx1

9 10

2nd method: Threads by implementing


Runnable interface An example
class MyThread implements Runnable
{ class MyThread implements Runnable {
..... public void run() {
public void run() System.out.println(" this thread is running ... ");
{ }
// thread body of execution } // end class MyThread
}
} class ThreadEx2 {
• Creating Object: public static void main(String [] args ) {
MyThread myObject = new MyThread(); Thread t = new Thread(new MyThread());
• Creating Thread Object: // due to implementing the Runnable interface
Thread thr1 = new Thread( myObject ); // I can call start(), and this will call run().
• Start Execution: t.start();
thr1.start(); } // end main()
} // end class ThreadEx2

11 12

2
Life Cycle of Thread A Program with Three Java Threads

new • Write a program that creates 3 threads


wait()
start() sleep()
suspend()
blocked
runnable non-runnable

notify()
stop()
slept
resume()
dead unblocked
13 14

Three threads example


class A extends Thread class C extends Thread
{ {
public void run() public void run()
{
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i); for(int k=1;k<=5;k++)
} {
System.out.println("\t From ThreadC: k= "+k);
System.out.println("Exit from A"); }
}
System.out.println("Exit from C");
} }
class B extends Thread
{ }
public void run()
{
class ThreadTest
for(int j=1;j<=5;j++) {
{ public static void main(String args[])
System.out.println("\t From ThreadB: j= "+j);
} {
new A().start();
System.out.println("Exit from B");
new B().start();
}
new C().start();
}
}
16
}

Run 1 Run2
• [test@root] threads [1:76] java ThreadTest • [raj@mundroo] threads [1:77] java ThreadTest
From ThreadA: i= 1 From ThreadA: i= 1
From ThreadA: i= 2 From ThreadA: i= 2
From ThreadA: i= 3 From ThreadA: i= 3
From ThreadA: i= 4 From ThreadA: i= 4
From ThreadA: i= 5 From ThreadA: i= 5
Exit from A From ThreadC: k= 1
From ThreadC: k= 1 From ThreadC: k= 2
From ThreadC: k= 2 From ThreadC: k= 3
From ThreadC: k= 3 From ThreadC: k= 4
From ThreadC: k= 4 From ThreadC: k= 5
From ThreadC: k= 5 Exit from C
Exit from C From ThreadB: j= 1
From ThreadB: j= 1 From ThreadB: j= 2
From ThreadB: j= 2 From ThreadB: j= 3
From ThreadB: j= 3 From ThreadB: j= 4
From ThreadB: j= 4 From ThreadB: j= 5
From ThreadB: j= 5 Exit from B
Exit from B Exit from A

17 18

3
the driver: 3rd Threads sharing the same
Shared Resources object
• If one thread tries to read the data and other thread class InternetBankingSystem {
tries to update the same date, it leads to inconsistent public static void main(String [] args ) {
state. Account accountObject = new Account ();
• This can be prevented by synchronising access to Thread t1 = new Thread(new MyThread(accountObject));
data. Thread t2 = new Thread(new YourThread(accountObject));
Thread t3 = new Thread(new HerThread(accountObject));
• In Java: “Synchronized” method: t1.start();
– syncronised void update() t2.start();
–{ t3.start();
• … // DO some other operation
–} } // end main()
}
19 20

Program with 3 threads and


shared object Monitor (shared object) example
class MyThread implements Runnable {
Account account; class Account { // the 'monitor'
public MyThread (Account s) { account = s;} // DATA Members
int balance;
public void run() { account.deposit(); }
} // end class MyThread // if 'synchronized' is removed, the outcome is unpredictable
public synchronized void deposit( ) {
class YourThread implements Runnable { // METHOD BODY : balance += deposit_amount;
Account account; }
public YourThread (Account s) { account = s;
} account public synchronized void withdraw( ) {
public void run() { account.withdraw(); } // METHOD BODY: balance -= deposit_amount;
} // end class YourThread }
public synchronized void enquire( ) {
// METHOD BODY: display balance.
class HerThread implements Runnable { }
Account account; }
public HerThread (Account s) { account = s; }
public void run() {account.enquire(); }
21 22
} // end class HerThread

Thread Priority Thread Priority Example


class A extends Thread
• In Java, each thread is assigned priority, which affects {
public void run()
{
the order in which it is scheduled for running. The System.out.println("Thread A started");

for(int i=1;i<=4;i++)
threads so far had same default priority {
System.out.println("\t From ThreadA: i= "+i);
}
(ORM_PRIORITY) and they are served using FCFS System.out.println("Exit from A");
}
policy. }

– Java allows users to change priority: class B extends Thread


{
public void run()
• ThreadName.setPriority(intNumber) {
System.out.println("Thread B started");
– MIN_PRIORITY = 1 for(int j=1;j<=4;j++)
{
– NORM_PRIORITY=5 System.out.println("\t From ThreadB: j= "+j);
}
– MAX_PRIORITY=10 System.out.println("Exit from B");
}

23 24

4
Thread Priority Example
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");

for(int k=1;k<=4;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");
threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();
System.out.println("End of main thread");
25 }
}

You might also like