Вы находитесь на странице: 1из 44

Basic Java

Unit 10 Multi Threading

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Unit 10 Multi Threading

Topics

What are threads ? Need for Multiple Threads Time Scheduling Creating multiple threads Thread class The Runnable interface Thread priorities sleep() and join() Daemon threads The problems that comes with parallelism What are race conditions? Thread synchronization Synchronizing critical code Synchronized method() Vs Synchronized block

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

What is a Thread ?

A Thread is a single sequential flow of control within a program. It is an independently running subtask.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Multiple Threads

A program having multiple threads implies that there are multiple flows of execution within the program
Sub tasks that are executing in parallel

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Need for Multiple Threads

Let us suppose that we have to develop an application that is similar to Windows search
What are the different functionalities that we identify ?

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Need for Multiple Threads


2. Display files that match the criteria

1. Perform search

3. Scroll the progress bar

4. Puppy animation

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Need for Multiple Threads


class SearchDemo { public static void main() { WindowsSearch ws = new WindowsSearch(); ws.search(fileName); ws.scrollProgressBar(); ws.animatePuppy(); ws.displayFiles(); } }

Look at the below code snippet


public class WindowsSearch { public void search(String fileName) { // Implementation } public void scrollProgressBar() { // Implementation } public void animatePuppy() { // Implementation } public void displayFiles() { // Implementation } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

What is the problem ?


Search Scroll Progress Bar

Puppy Animation

Display files

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Need for Multiple Threads


Scroll Progress Bar Puppy Animation Display files

What we desire to achieve is parallel processing


Search

Every task is processed by one thread All four threads execute almost at the same time

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Threads and Scheduling

Each thread is given a small amount of processor time called a quantum or timeslice, with which to perform its task. When the threads quantum expires, the threads execution is paused. The operating system then assigns another thread to the processor. In this way, the CPU does a round robin of all threads.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Why use Threads ?

Threads can be used in numerous scenarios


To improve the responsiveness of application. To separate out data processing and input/output operations.
For non blocking input/output operations.

To handle asynchronous events (event handling such as a mouse click). Management of multiple service request with unpredictable arrival. To perform repetitive or timed tasks (animations).

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Threading API

The Java platform is designed from ground up to support multi threaded programming
Provides the developers with a simple Threading API

java.lang package offers a Thread class and a Runnable interface


Developers can spawn multiple threads by making use of these java artifacts. Developers are completely shielded from the internal working of threads.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

How to create threads ?

There are two ways in which we can create threads in Java


By extending the Thread class By implementing the Runnable Interface

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Class Thread
The Thread class sits on top of a platform dependent implementation of threads. A thread can be provided with a name, or a Runnable object at the time of its creation. The start() method is an important method that actually interfaces with the OS to spawn an OS-level thread
It is implemented in native code

The run() method is meant to contain the code to be executed in the thread.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Creating a Thread

Steps Involved
Define a class that extends Thread. Override the run() method Instantiate the class Spawn the thread by making a call to start() method start() method automatically calls run() and triggers execution of the thread.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Example
class ThreadDemo { public static void main(String[] s) { for(int i=0;i<=3;i++) new SimpleThread(). start(); System.out.println("All Threads Started"); } }

class SimpleThread extends Thread { private int countDown = 5; private static int trdCount = 0; private int trdNum = ++trdCount; SimpleThread() { System.out.println("Making thread " + trdNum); } public void run() { while(true) { System.out.println("Thread + trdNum + "( + countDown+")"); if(--countDown == 0) return; } } }
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Executing SimpleThread
Main thread executing
Thread 1 executing

Main thread executing Thread 2 executing

Thread 3 executing

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

How does it work ?


An instance of SimpleThread is created

SimpleThread t1 = new SimpleThread();


The JVM interfaces with the OS and an OS level thread is spawned

t1.start();
start() calls run()

public void run() { while(true) { System.out.println("Thread + trdNum + "( + countDown+")"); if(--countDown == 0) return; } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Interface Runnable
The Runnable interface defines the contract of making an object capable of being run by a thread The Runnable interface defines a single method, run()
meant to contain the code to be executed in the thread.

A class that implements this interface has to provide the implementation for run() method
An object of this class becomes a runnable object

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Creating a Thread

Steps Involved
Define a class that implements Runnable interface. Provide implementation for the run() method Instantiate the class
The object is now a Runnable object

Create a Thread instance and assign the Runnable object to the thread. Spawn the thread by making a call to start() method start() method automatically calls run() and triggers execution.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Example

class NewThread implements Runnable { int start,stop; NewThread(int start,int stop) { this.start=start; this.stop=stop; } public void run() { for(int i=stop;i>start;i--) System.out.println(Thread.currentThread() + " : " + i); System.out.println("Exiting " + Thread.currentThread()); } }
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Example

class RunnableDemo { public static void main(String args[]) { NewThread nt1=new NewThread(5,10); NewThread nt2=new NewThread(15,18); Thread t1 = new Thread(nt1); Thread t2 = new Thread(nt2); System.out.println(Starting Thread 1 ); t1.start(); System.out.println(Starting Thread 2 ); t2.start(); System.out.println("Main thread exiting"); } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

How does it work ?


Runnable instance is created

NewThread nt1=new NewThread(5,10); Thread t1 = new Thread(nt1);

t1.start(); start() calls run()

The JVM interfaces with the OS and an OS level thread is spawned

Thread object is created and given the runnable reference

public void run() { for(int i=stop;i>start;i--) System.out.println(Thread.currentThread() + " : " + i); System.out.println("Exiting " + Thread.currentThread()); }
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Thread Priorities

A CPU can execute only one thread at a time


The threads that are ready for execution queue up for processor time.

So the threads are executed depending on their priority, relative to one another. A threads priority is used to decide when to switch from one running thread to the next, which is called context switching. Higher priority threads get more CPU time

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Thread Priorities

All threads inherit their priority from the thread that created it. Thread priorities are between 1 and 10.
Ten is the highest priority (MAX_PRIORITY) One is the lowest (MIN_PRIORITY) Five is the default priority (NORM_PRIORITY)

Threads can be assigned a priority using the setPriority() method of the Thread class.
void setPriority(int newPriority)

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

sleep() method

public static void sleep(long millis)


Causes the thread to cease execution for the specified number of milliseconds Throws InterruptedException if interrupted by another thread

See SleepDemo.java
Copyright 2008 Pratian Technologies www.pratian.com

For the time that T1 is sleeping, another Thread T2 is allowed to execute

Basic Java

Unit 10 Multi Threading

join() method

public void join()


Causes the currently executing thread to wait for another thread to finish
Thread1 will not execute till the time Thread2 completes executing fully

See JoinDemo.java
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Other methods

boolean isAlive()
Determines if the thread is still running.

int getPriority()
Returns the threads priority.

String getName()
Returns the threads name.

setName(String name)
Changes the name of this thread to the specified string.

static Thread currentThread()


Returns a reference to the currently executing thread object

toString()
Returns a string representation of this thread, including the thread's name, priority, and thread group.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Daemon Threads

Daemon threads are service providers for other threads Daemon Threads running in the same process as the daemon thread.
Like the garbage collector thread, the finalizer thread that are daemon threads executing within the JVM

The run() method for a daemon thread is typically an infinite loop that waits for a service request. Daemon threads keep executing until there is atleast one active non daemon thread.
When the only remaining threads in a process are daemon threads, the process terminates.
If daemon threads run incessantly, when do they terminate ?

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Daemon Threads

Daemon a daemon To specify that a thread isThreads thread, call the setDaemon() method of Thread class with the argument true.
This method must be called before invoking the start method on the thread.

Every thread acquires its daemon property from its parent thread.
Threads created by daemon threads are all daemon by default. Threads created by non daemon threads are non daemon by default. See DaemonDemo.java
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Concurrent Access

Sharing data among threads could cause inconsistencies, when multiple threads access the same object at the same time.
Consider the below example Booking Thread Ticket Counter updateCount() getCount() Cancellation Thread

Updates ticket count when member books tickets online

Updates ticket count when member cancels ticket online

Display Thread

Displays available number of tickets

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Concurrent Access
class Counter { private static int count = 100; public void updateCount (int numOfTickets) { this.count = numOfTickets; } public int getCount() { return count; } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Concurrent Access
class CancellationThread extends Thread { private Counter count; CancellationThread (Counter count) { this.count = count; } public void run() { // some logic count.updateCount (val); } }

class BookingThread extends Thread { private Counter count; BookingThread(Counter count) { this.count = count; } public void run() { // some logic if(success) count.updateCount (val); } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Concurrent Access
class BookingAppDemo { public static void main (String[] args) { Counter c = new Counter(); BookingThread t1 = new BookingThread(c); CancellationThread t2 = new CancellationThread(c); DisplayThread t3 = new DisplayThread(); t1.start(); t2.start(); t3.start(); } }

class DisplayThread extends Thread { private Counter count; DisplayThread(Counter count) { this.count = count; } public void run() { // some logic System.out.println (count.getCount()); } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Problems that come with Parallelism

Scenario 1
BookingThread is in the process of making checks and decrementing count, just then DisplayThread accesses Counter to view count.
DisplayThread is not guaranteed to get the same count if BookingThread successfully processes and decrements count, leading to inconsistent data.

Scenario 2
BookingThread is trying to decrement CancellationThread is concurrently invoked count, just then
Both threads try to make changes to Ticket count, concurrently

See RaceConditionDemo.java

This would result in a race condition

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Race Conditions

A race condition is a programming fault which produces unpredictable program state and behavior due to un-synchronized concurrent executions. Race Conditions can occur when two or more threads race to update the same data structure at the same time. The result can be partly what one thread wrote and partly what the other thread wrote. This garbles the data structure, or can cause the next thread that tries to use it to crash What is the
primary cause for such race conditions ?
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Race Conditions

What is the primary cause for such a race condition ?

Counter

What is the possible work around ?

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Synchronizing Access

Synchronization makes access to the object restricted to only one thread at a time. The Java platform associates a lock with every object that has synchronized code.
Booking Thread Cancellation Thread Display Thread
Counter

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Synchronization

The code segments within a program that access the same object from separate, concurrent threads are called critical sections. Synchronization avoids race conditions by ensuring mutual exclusion to critical sections. Every class that has synchronized code is considered to be a monitor. A monitor operates by ensuring that at most one thread can execute the synchronized code within the object at any one time.

A critical section can be a method or a few statements & is identified with the synchronized modifier.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Synchronized Methods

To make a method synchronized, the synchronized keyword is added to its declaration. class Counter { private static int count = 100; public synchronized void updateCount (int numOfTickets) { this.count = numOfTickets; } public synchronized int getCount() { return count; } }
Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Synchronized Methods

Once a thread enters any synchronized method on an instance, no other thread can enter any other synchronized method on the same instance.
Only one synchronized method of an object can be active at a time All other threads attempting to invoke a synchronized method are forced to wait.

Whenever a synchronized method is called, then the object to which the synchronized method belongs is locked. When a synchronized method finishes executing, the lock on the object is released
The lock release occurs even if the method returns due to an uncaught exception. The highest-priority ready thread attempting to provoke a synchronized method is then allowed to proceed.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Synchronized Blocks

We could lock on a portion of a method using synchronized blocks. Rather than declaring the entire method to be synchronized, a few lines of critical code can be synchronized. This can increase concurrency and improve performance. Synchronized blocks place locks for shorter periods than synchronized methods.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Synchronized Blocks

Unlike synchronized methods, synchronized block must specify the object on which we wish to hold the lock.
class Counter { private int count = 0; public void updateCount(int numOfTickets) { // some code synchronized(this) { count = numOfTickets; } // some more code } }

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Unit 10 Multi Threading

Question time

Please try to limit the questions to the topics discussed during the session. Thank you.

Copyright 2008 Pratian Technologies www.pratian.com

Basic Java

Вам также может понравиться