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

Multithreading Bca

Multithreading is a programming technique that allows multiple threads to run concurrently within a single process, enhancing efficiency and resource utilization. Java's multithreading is facilitated through the Thread class and the Runnable interface, enabling developers to create and manage threads effectively. Key concepts include thread states, lifecycle, priority management, and methods for creating and controlling threads.

Uploaded by

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

Multithreading Bca

Multithreading is a programming technique that allows multiple threads to run concurrently within a single process, enhancing efficiency and resource utilization. Java's multithreading is facilitated through the Thread class and the Runnable interface, enabling developers to create and manage threads effectively. Key concepts include thread states, lifecycle, priority management, and methods for creating and controlling threads.

Uploaded by

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

MULTITHREADING

Note: pls refer Balagurusamy for this


chapter
• Multithreading is a technique that allows 2/more parts of
your program to run concurrently.
• Each such part is called as a “thread” which defines a
separate execution path.
• Specialised form of multitasking. Also called as thread based
multitasking.
• Basically, threads are part of a process which share its
address space & run concurrently.
• For eg. A word application (program) is simultaneously spell
checking, & at the same time its printing the user’s input. So
there is a thread for spell checking & another thread for
printing ,both of which are executing inside the application.
Advantages of Multithreading
• Multithreading enables writing very efficient programs that
make maximum use of the CPU, because idle time can be kept
to a minimum.

• The benefit of Java’s multithreading is that one thread can


pause without stopping other parts of your program. For
example, the idle time created when a thread reads data from a
network or waits for user input can be utilized elsewhere.
Multithreading allows animation loops to sleep for a second
between each frame without causing the whole system to
pause.

• When a thread blocks in a Java program, only the single thread


that is blocked pauses. All other threads continue to run.
A single threaded program
class ABC
{
….
public void main(..) begin
{
… body
..
end
}
}

4
A Multithreaded Program

Main Thread
(Main method)

start
start start

Thread A Thread B Thread C

Threads may switch or exchange data/results


5
Process based multitasking Thread Based Multitasking
• Process is a program in • Threads are parts of
execution. processes.
• Processes have their own • Threads share the address
address space space of the process.
• It allows computer to run • allows 2/more parts of your
2/more programs to run program to run concurrently
concurrently.
Eg. Working on a word file &
at the same time a file is
being downloaded from the
internet.
• Requires less overhead
• Requires more overhead
• Context switching is easy.
• Context switching is
expensive
Thread States

• Thread States and Life Cycle


• Every thread has a life cycle that consists of several
different states, as summarized in Figure and Table .
Thread states are represented by labeled ovals, and
transitions between states are represented by labeled
arrows. Much of a thread's life cycle is under the
control of the operating system and the Java Virtual
machine. Transitions represented by method names
such as start() ,stop() , wait() , sleep() , notify() can
be controlled by the program.
Thread Class and the Runnable Interface

● Java’s multithreading system is built upon the


Thread class, its methods, and its companion
interface, Runnable
● To create a new thread your program will
either extend thread, Thread or implement
the Runnable interface.
● The Thread class defines several methods
that help manage threads.
Thread Class Constructors
• Thread class defines several constructors that
are used to create threads.
• Some of them are:
a) Thread()
b) Thread (String thread name)
c) Thread(Runnable r)
Thread Class methods
Thread Life Cycle
• Thread States:
• A thread can be in one of the following states
• New born state
• Ready to run state
• Running state
• Blocked state
• Dead state
• New Born state
• The thread enters the new born state as soon as it is created. The thread is
created using the new operator.
• From the new born state the thread can go to ready to run mode or dead
state.
• If start( ) method is called then the thread goes to ready to run mode. If the
stop( ) method is called then the thread goes to dead state.

• Ready to run mode (Runnable Mode)


• If the thread is ready for execution but waiting for the CPU the thread is said
to be in ready to run mode.
• All the events that are waiting for the processor are queued up in the ready
to run mode and are served in FIFO manner or priority scheduling.
• From this state the thread can go to running state if the processor is available
using the scheduled( ) method.
• From the running mode the thread can again join the queue of runnable
threads.
• The process of allotting time for the threads is called time slicing.
• Running state
• If the thread is in execution then it is said to be in running state.
• The thread can finish its work and end normally.
• The thread can also be forced to give up the control when one of the following
conditions arise.
1. A thread can be suspended by suspend( ) method. A suspended thread can be
revived by using the resume() method.
2. A thread can be made to sleep for a particular time by using the
sleep(milliseconds) method. The sleeping method re-enters runnable state when
the time elapses.
3. A thread can be made to wait until a particular event occur using the wait()
method, which can be run again using the notify( ) method.
• Blocked state
• A thread is said to be in blocked state if it prevented from entering into the
runnable state and so the running state.
• The thread enters the blocked state when it is suspended, made to sleep or wait.
• A blocked thread can enter into runnable state at any time and can resume
execution.
• Dead State
• The running thread ends its life when it has
completed executing the run() method which
is called natural dead.
• The thread can also be killed at any stage by
using the stop( ) method.
Threading Mechanisms...
• Create a class that extends the Thread class
• Create a class that implements the Runnable
interface

16
Creating thread using Thread class
• One way of creating thread is to extend the Thread class. The steps to
create a thread using thread class is as follows:
• 1.Derive a subclass from class Thread.
• 2.Override the run( ) method in the class.
• Syntax:
• class classname extends Thread
{
-------
-------
public void run()
{
//statements
}
}
• 3. Create an instance of the subclass.
• 4. Call the start( ) method of class Thread. The start( ) calls run() method.

17
1st method: Extending Thread class
 Threads are implemented as objects that contains a method
called run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
 Create a thread:
MyThread thr1 = new MyThread();
 Start Execution of threads:
thr1.start();

18
An example
class MyThread extends Thread { // the thread
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread

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();
19
} // end main()
2nd method: Threads by implementing
Runnable interface
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
 Creating Object:
MyThread myObject = new MyThread();
 Creating Thread Object:
Thread thr1 = new Thread( myObject );
 Start Execution:
thr1.start();

20
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread

class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// I can call start(), and this will call run().
t.start();
} // end main()
} // end class ThreadEx2

21
A Program with Three Java Threads
• Write a program that creates 3 threads

22
Three threads example
class A extends Thread
{ public void run()
{for(int i=1;i<=5;i++)
{ System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A"); }}

class B extends Thread


{ public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}

System.out.println("Exit from B");


}}

23
class C extends Thread
{ public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}

System.out.println("Exit from C");


}
}
class ThreadTest
{
public static void main(String args[])
{
A a=new A();
a.start();

B b=new B();
b.start();

C c=new C();
c.start();

}}
24
Run 1
java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B

25
Run2
java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A

26
Exercise
• WAP that makes use of 3 threads.
• Thread A : print no.s from 1 to 5
• Thread B : print no.s from 6 to 10
• Thread C : print no.s from 11 to 15
Sleep Method
• The sleep() method of Thread class is used to sleep a thread
for the specified amount of time.

• Syntax of sleep() method in java

• public static void sleep(long miliseconds)throws


InterruptedException
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++)
{
try{ Thread.sleep(500); }

catch(InterruptedException e)
{System.out.println(e);}

System.out.println(i);
} Output:
} 11223344
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}
Thread Priority
• In Java, each thread is assigned priority, which affects
the order in which it is scheduled for running. The
threads so far had same default priority
(NORM_PRIORITY) and they are served using FCFS
policy.
– Java allows users to change priority:
• ThreadName.setPriority(intNumber)
– MIN_PRIORITY = 1
– NORM_PRIORITY=5
– MAX_PRIORITY=10

30
Thread Priorities

● To set a thread’s priority, use the setPriority( ) method, which


is a member of Thread. This is its general form:
final void setPriority(int level)
● Here, level specifies the new priority setting for the calling
thread. The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.

● Currently, these values are 1 and 10, respectively. To return a


thread to default priority, specify NORM_PRIORITY, which is
currently 5. These priorities are defined as final variables
within Thread.
● You can obtain the current priority setting by calling the
getPriority( ) method of Thread, shown here:
final int getPriority( )
Thread Priority Example
class A extends Thread
{
public void run()
{
System.out.println("Thread A started");

for(int i=1;i<=4;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}

System.out.println("Exit from A"); }}


class B extends Thread
{ public void run()
{ System.out.println("Thread B started");
for(int j=1;j<=4;j++)
{ System.out.println("\t From ThreadB: j= "+j);
} System.out.println("Exit from B");
}}
32
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"); }}

33
output
Thread Class and the Runnable Interface

● Java’s multithreading system is built upon the


Thread class, its methods, and its companion
interface, Runnable
● To create a new thread your program will
either extend thread, Thread or implement
the Runnable interface.
● The Thread class defines several methods
that help manage threads.
Main Thread
● When a Java program begins, one thread begins running immediately.
This is usually called the main thread of your program, because it is the
one that is executed when your program begins. The main thread is
important for two reasons:
■ It is the thread from which other “child” threads will be spawned.
■ Often it must be the last thread to finish execution because it performs
various shutdown actions.
● Although the main thread is created automatically when your program
begins, it can be controlled through a Thread object. To do so, you
must obtain a reference to it by calling the method currentThread( ),
which is a public static member of Thread class. Its general form is
shown here:

static Thread currentThread( )


● This method returns a reference to the thread in which it is called. A
reference to the main thread, allows controlling it just like any other
Thread.
Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread(); // obtain ref to current thread
System.out.print("Current thread: " + t); // print desc. Of the thread
t.setName("My Thread"); // change the name of the thread

System.out.print("After name change: " + t);


try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);} // thread sleeps for 1sec.
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");}}}
output
Current Thread:Thread[main,5,main]
After name change:Thread[My Thread,5,main]
5
4
3
2
1
Implementing Runnable
1.A thread can be created by creating a class that
implements the Runnable interface.
2. To implement Runnable, a class need only
implement a single method called run( ), which
is declared like this:

public void run( )


Inside run( ), you will define the code that
constitutes the new thread.
2nd method: Threads by implementing
Runnable interface
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
 Creating Object:
MyThread myObject = new MyThread();
 Creating Thread Object:
Thread thr1 = new Thread( myObject );
 Start Execution:
thr1.start();

40
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread

class ThreadEx2 {
public static void main(String [] args ) {
Mythread ob=new Mythread();
Thread t = new Thread(ob);
// due to implementing the Runnable interface
// I can call start(), and this will call run().
t.start();
} // end main()
} // end class ThreadEx2

41
Exercise
• WAP that creates two threads:
• A: prints table of 4
• B: prints table of 11
• Use Runnable Interface.
The join() method

• The join() method waits for a thread to die. In


other words, it causes the currently running
threads to stop executing until the thread
invoking the join() completes its task.
• This method waits until the thread on which it
is called terminates.
class Multi extends Thread{
public void run(){
for(int i=3;i>0;i--){
try{ Thread.sleep(500);
}catch (Interrupted Exception e){
System.out.println(e);}
System.out.println(i);
} }
public static void main(String args[]){
Multi t1=new Multi();
Multi t2=new Multi();
Multi t3=new Multi();
t1.start();
//System.out.println(“Thread 1 alive = " + t1.isAlive()); //will print true
try{
t1.join(); // wait till t1 executes completel
} catch(Exception e){System.out.println(e);}
t2.start();
t3.start(); }}
• Output
• Thread 1 alive:true
• 3
• 2
• 1
• 3
• 3
• 2
• 2
• 1
• 1
• See that since join was called by t1 ( 1st thread), so that
thread will completely execute & after that switching will
take place between t2 & t3.
Synchronization
• Simultaneous access & manipulation & of a share resource can lead
to an incorrect output When2/more threads need to access a shared
resource , they has to be some way to ensure that only 1 thread is
accessing the resource at a time.. The process by which this is
achieved is called as synchronization.
• Java provides unique, language-level support for Synchronization.
• Threads are synchronised in Java via monitors.
• Each object in Java is associated with a monitor. Only one thread can
own a monitor at a given time.
• When a thread enters the monitor ,all other threads attempting to
enter the locked monitor will be suspended until the first thread
exits the monitor. These other threads are said to be waiting for the
monitor.
• Monitor provides a mutual exclusive access to the shared resource.
Its just like semaphore.
..contd
• One can synchronize code in either of two
ways. Both involve the use of the
synchronized keyword, and both are
examined here:
• i) Using Synchronized Methods
• ii) The synchronized Statement
Synchronized Method :Syntax
• synchronized method_name {
– Code to be synch.
–}
• Eg. Synchronized void update(){
– Code to be synch.
–}
Using Synchronized Methods

• Whenever we declare declare any method as


synchronized, it means that only one thread
can access that method at a time
• While a thread is inside a synchronized
method, all other threads that try to call it (or
any other synchronized method) on the same
instance have to wait.
• In this way, we ensure serialization , exclusive
access & prevent race condition.
class Buying implements Runnable{ class Synch_demo{
int item_avail=1; public static void main (String []args){
synchronized public void run(){ Buying ob=new Buying();
{ Thread t1= new Thread(ob);
System.out.println("Items Thread t2= new Thread(ob);
available:"+item_avail); t1.start();
if(item_avail!=0){ t2.start();
System.out.println("order placed }}
successfully");
try{
Thread.sleep(1000);
item_avail=0;
}
catch(InterruptedException e){}
}
else
System.out.println("Sorry, out of stock");}}}
Synchronized block
• This is the general form of the synchronized block:
Synchronized block can be used to perform synchronization
on any specific resource of the method.
• Suppose you have 50 lines of code in your method, but you
want to synchronize only 5 lines, you can use synchronized
block.
• If you put all the codes of the method in the synchronized
block, it will work same as the synchronized method.

synchronized(object) { // statements to be synchronized }


Object is a reference to the object being synchronized
wait(), notify() and notifyAll()

● wait( ) tells the calling thread to give up the monitor and go to


sleep until some other thread enters the same monitor and calls
notify( ).
● ■ notify( ) wakes up the first thread that called wait( ) on the
same object.
● ■ notifyAll( ) wakes up all the threads that called wait( ) on the
same object.
● The highest priority thread will run first.
● These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
● Additional forms of wait( ) exist that allow you to specify a
period of time to wait.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy