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

Unit 2_2

X
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)
13 views

Unit 2_2

X
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/ 40

Multithreaded Programming &

Input / Output
Java Thread
• Earlier we were unable to run more than one task in parallel. It was a
drawback, and to remove that drawback, Thread Concept was
introduced.
• A Thread is a very light-weighted process, or we can say the smallest
part of the process that allows a program to operate more efficiently
by running multiple tasks simultaneously.
• Threads have a separate path of execution.
• All the tasks are executed without affecting the main program.
• In a program or process, all the threads have their own separate path
for execution, so each thread of a process is independent.
• if a thread gets an exception or an error at the time of its execution, it
doesn't affect the execution of the other threads.
Prepared By Joylin Priya Pinto 2
• All the threads share a common memory and have their own stack, local
variables and program counter.

• When multiple threads are executed in parallel at the same time, this process is
known as Multithreading.
Prepared By Joylin Priya Pinto 3
Single and Multithreaded
Processes

4
• A multithreaded program contains two or more parts that can run
concurrently.
• Each part of such a program is called a thread, and each thread
defines a separate path of execution. Multithreading is a
specialized
form of multitasking.
• There are two types of multitasking : process-based, thread-based.
• Processes-based multitasking is the feature that allows your
computer to run two or more programs concurrently.
• Ex : process-based multitasking enables you to run the Java
compiler at the same time when using a text editor.
• In thread-based multitasking a single program can perform two or
more tasks simultaneously.
• Ex : A text editor can format text at the same time that it is
printing. 5
Threads exist in several states:
• A thread can be running. It can be ready to run as
soon as it gets CPU time.
• A running thread can be suspended, which temporarily
suspends its activity.
• A suspended thread can then be resumed, allowing it
to pick up where it left off.
• A thread can be blocked when waiting for a resource.
• At any time, a thread can be terminated, which halts
its execution immediately. Once terminated, a thread
cannot be resumed.

Prepared By Joylin Priya Pinto 6


Life Cycle of a Thread
A thread goes through various stages in its life cycle. For
example, a thread is born, started, runs, and then dies. The
following diagram shows the complete life cycle of a thread.

Prepared By Joylin Priya Pinto 7


Following are the stages of the life cycle −
• New − A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as
a born thread.
• Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
Thread Scheduler provides the thread time for the runnable state
preserved threads.
• Waiting − Sometimes, a thread transitions to the waiting state while
the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread signals
the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state
for a specified interval of time. A thread in this state transitions back to
the runnable state when that time interval expires or when the event it
is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state
Prepared By Joylin Priya Pinto 8
when it completes its task or otherwise terminates.
The Thread Class and Runnable Interface
• Java’s multithreading system is built upon the Thread class and its
companion interface, Runnable.
• To create a new thread, your program will either extend Thread or
implement the Runnable interface.
• The Thread class defines several methods that help manage
threads.

9
The Main Thread
• When a Java program starts up, one thread begins running
immediately. This is usually called the main thread of our
program.
• 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.
• Main thread can be controlled through a Thread object.
• To do so, we must obtain a reference to it by calling the method
currentThread(), a public static member of Thread.

10
class CurrentThreadDemo {
public static void main(String args[]) {
Changes the name of
Thread t = Thread.currentThread();
the thread from main
System.out.println("Current thread: " + t); to “My Thread”
t.setName("My Thread");
System.out.println("After name change: " + t);
try { 1.sleep method to pause.
for(int n = 5; n > 0; n--) { 2. The argument
System.out.println(n); specifies the delay in
Thread.sleep(1000); milliseconds.
} 3. It might throw an
} catch (InterruptedException e) { interrupted exception.
System.out.println("Main thread interrupted");
}
}
}
11
The name of the thread, its
priority and the name of its
group.

Current thread: Thread[main,5,main]


After name change: Thread[My Thread,5,main]
5 Thread name
4 changed, 5 is the
3 default priority of any
2 thread, main is the
1 name of its group.
12
Creating a Thread
• We can create a thread by instantiating an object of type Thread.
• Java defines two ways in which you can create a runnable object:
• You can implement the Runnable interface.
• You can extend the Thread class.

13
Creating Thread by extending Thread Class

import java.io.*;
import java.util.*;

public class test extends Thread {


// initiated run method for Thread
public void run()
{
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{
test t1 = new test();
// Invoking Thread using start() method
t1.start();
}
}
Prepared By Joylin Priya Pinto 14
Example2: Sample Code to create Thread in Java using Thread(String name):
import java.io.*;
import java.util.*;

public class test1 {


public static void main(String args[])
{
// Thread object created and initiated with data
Thread t = new Thread("Hello NMAMIT!");

// Thread gets started


t.start();

// getting data of Thread through String


String s = t.getName();
System.out.println(s);
} Prepared By Joylin Priya Pinto 15
Eample:3
public class ThreadExample1 extends Thread {

// run() method to perform action for thread.


public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();

//calling start method to execute the run() method of the Thread class
t1.start();
}
} Prepared By Joylin Priya Pinto 16
start() method
• The method is used for starting a thread that we have newly created.
• It starts a new thread with a new call stack.
• After executing the start() method, the thread changes the state from New
to Runnable.
• It executes the run() method when the thread gets the correct time to
execute it.

Prepared By Joylin Priya Pinto 17


The Main Thread
When a Java program starts up, 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 is started, 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. Prepared By Joylin Priya Pinto 18
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");}
}
}
Prepared By Joylin Priya Pinto 19
Implementing Runnable
• The easiest way to create a thread is to create a class that
implements the Runnable interface.
• We can construct a thread on any object that implements the
Runnable interface. Runnable defines only one method called
run( ).
Usage : public void run()

Prepared By Joylin Priya Pinto 20


• Inside run( ), we write the code for the new thread.
• It is important to understand that run( ) can call other methods, use
other classes, and declare variables just like the main thread.
• The only difference is that run( ) establishes the entry point for
another, concurrent thread of execution within our program. This
thread will end when run( ) returns.
• After we have created a class that implements Runnable, we will
instantiate an object of type Thread on an object of that class.
• Thread defines several constructors. The one that we will use first
is shown here:
• Thread (Runnable threadOb, String threadName)
• In this constructor, threadOb is an instance of a class that
implements the Runnable interface. This defines where execution
of the thread will begin.
21
• The name of the new thread is specified by the threadName.
• Once created, the new thread will not start running until we call its
start( ) method, which is declared within Thread. Then, start()
executes a call to run( ) and returns to main function.

class NewThread implements Runnable Indicates we want the


{ new thread to call the
Thread t; run() method.

NewThread()
{ Starts the
// Create a new, second thread execution of
t = new Thread(this, "Demo Thread"); thread beginning
System.out.println("Child thread: " + t); at the run()
t.start(); method.
}
22
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
23
class ThreadDemo {
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
} 24
Creating Multiple Threads

Prepared By Joylin Priya Pinto 25


Prepared By Joylin Priya Pinto 26
Java Thread Priority in Multithreading
Thread priorities are used by the thread scheduler to decide
when each thread should be allowed to run. In theory, higher-
priority threads get more CPU time than lower-priority threads.
Thread priorities are integers that specify the relative priority of
one thread to another.
Whenever we create a thread in Java, it always has some
priority assigned to it. Priority can either be given by JVM while
creating the thread or it can be given by programmer explicitly.
Accepted value of priority for a thread is in range of 1 to 10.
There are 3 static variables defined in Thread class for priority.
public static int MIN_PRIORITY: This is minimum priority that
a thread can have. Value for this is 1.
public static int NORM_PRIORITY: This is default priority of a
thread if do not explicitly define it.PriyaValue
Prepared By Joylin Pinto for this is 5. 27
import java.lang.*;
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
System.out.println("t1 thread priority : " +
t1.getPriority()); // Default 5
System.out.println("t2 thread priority : " + t2.getPriority());
// Default 5 Prepared By Joylin Priya Pinto 28
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// t3.setPriority(21); will throw IllegalArgumentException
System.out.println("t1 thread priority : " +
t1.getPriority()); //2
System.out.println("t2 thread priority : " +
t2.getPriority()); //5
System.out.println("t3 thread priority : " + t3.getPriority());//8
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
}
}
Prepared By Joylin Priya Pinto 29
Example:
import java.lang.*;
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
Thread.currentThread().setPriority(6);
System.out.println("main thread priority : " +
Thread.currentThread().getPriority());
ThreadDemo t1 = new ThreadDemo();
System.out.println("t1 thread priority : “ + t1.getPriority());
}
} Prepared By Joylin Priya Pinto 30
The Thread class defines several methods that help manage threads:

Prepared By Joylin Priya Pinto 31


isAlive() and join() methods of Thread Class in Java
How can one thread know when another thread has
ended?
Thread provides a means by which you can answer this
question. Java multi-threading provides two ways to find that
isAlive() : It tests if this thread is alive. A thread is alive if it
has been started and has not yet died. There is a transitional
period from when a thread is running to when a thread is not
running. After the run() method returns, there is a short period
of time before the thread stops. If we want to know if the start
method of the thread has been called or if thread has been
terminated, we must use isAlive() method. This method is used
to find out if a thread has actually been started and has yet not
terminated.

Prepared By Joylin Priya Pinto 32


join() : When the join() method is called, the current thread
will simply wait until the thread it is joining with is no longer
alive. Or we can say the method that you will more
commonly use to wait for a thread to finish is called join( ).
final void join( ) throws InterruptedException
This method waits until the thread on which it is called
terminates. Its name comes from the concept of the calling
thread waiting until the specified thread joins it. Additional
forms of join( ) allow you to specify a maximum amount of
time that you want to wait for the specified thread to
terminate.
Example demonstrates that uses join( ) to ensure that the
main thread is the last to stop. It also demonstrates the
isAlive( ) method.
Prepared By Joylin Priya Pinto 33
join() and alive() Demonstration
class mthread extends Thread{
public void run(){
for (int i = 0; i <5; i++)
{
System.out.println("Child Thread " + i);
}
System.out.println("Exiting from Child Thread");
}
}
public class IsAlive_JoinDemo
{
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
mthread t=new mthread();
t.start();
try {
System.out.println("Child Thread "+i+" is
alive:"+t.isAlive());
t.join();
} catch (InterruptedException e) { }
System.out.println("Child Thread "+i+"
Prepared Byis
Joylinalive:"+t.isAlive());
Priya Pinto 34
for (int j = 0; j < 5; j++) Child Thread 1 is alive:false
{ Child Thread 2 is alive:true
System.out.println("Main Thread " + j); Child Thread 0
} Child Thread 1
System.out.println("Exiting from Main Thread"); Child Thread 2
} Child Thread 3
} Child Thread 4
Exiting from Child Thread
Output: Child Thread 2 is alive:false
Child Thread 0 is alive:true Child Thread 3 is alive:true
Child Thread 0 Child Thread 0
Child Thread 1 Child Thread 1
Child Thread 2 Child Thread 2
Child Thread 3 Child Thread 3
Child Thread 4 Child Thread 4
Exiting from Child Thread Exiting from Child Thread
Child Thread 0 is alive:false Child Thread 3 is alive:false
Child Thread 1 is alive:true Main Thread 0
Child Thread 0 Main Thread 1
Child Thread 1 Main Thread 2
Child Thread 2 Main Thread 3
Child Thread 3 Main Thread 4
Child Thread 4 Exiting from Main Thread 35
Prepared By Joylin Priya Pinto
Exiting from Child Thread
Synchronization
When two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used by
only one thread at a time. The process by which this is achieved
is called synchronization.
Key to synchronization is the concept of the monitor (also called
a semaphore). A monitor is an object that is used as a mutually
exclusive lock, or mutex. Only one thread can own a monitor at
a given time. When a thread acquires a lock, it is said to have
entered 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. A thread that
owns a monitor can reenter the same monitor if it so desires.

Prepared By Joylin Priya Pinto 36


Java provides a way of creating threads and synchronizing their
task by using synchronized blocks. Synchronized blocks in Java
are marked with the synchronized keyword. A synchronized
block in Java is synchronized on some object. All synchronized
blocks synchronized on the same object can only have one
thread executing inside them at a time. All other threads
attempting to enter the synchronized block are blocked until
the thread inside the synchronized block exits the block.

Prepared By Joylin Priya Pinto 37


Prepared By Joylin Priya Pinto 38
Prepared By Joylin Priya Pinto 39
• The general form of the synchronized statement: synchronized(object)
{ // statements to be synchronized }

Prepared By Joylin Priya Pinto 40

You might also like