320 likes | 334 Views
Chapter 7. Multithreaded Programming in Java. Agenda. Introduction to Threads Multitasking , Multithreading and Benefits Threads in Java Life cycle of a Thread States of Thread Creating Threads Thread Priorities Thread Synchronization Inter-thread Communication.
E N D
Chapter 7 Multithreaded Programming in Java
Agenda • Introduction to Threads • Multitasking, Multithreading and Benefits • Threads in Java • Life cycle of a Thread • States of Thread • Creating Threads • Thread Priorities • Thread Synchronization • Inter-thread Communication
Introduction to Threads “A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Java thread can be used to execute multiple tasks at the same time. “ Multitasking In computing, multitasking is a method by which multiple tasks, also known as processes, share common processing resources such as a CPU.
Introduction to Threads – Contd., • A process that is made of one thread is known as single- threaded process. • A process that creates two or more threads is called Multi-threaded process.
Multithreading • “ Multithreading is the system environment where the tasks are sharing the same program under the multitasking environment. • Multithreading is a subset of multitasking,since it concersn tasks which use the same program. • Under the multithreading environment, a program is shared by several tasks concurrently. • For each task, the program must work as if it were executing instructions exclusively for each task.”
Threads in Java • The java.lang.Thread class is used to construct and access individual threads in a multithreaded application. • It provides a thread API and all the generic behavior for threads. • These behaviors include starting, sleeping, running, yielding, and having a priority.
Threads in Java – Contd., Task of a Thread is defined in run() method: • The run() method gives a thread something to do. Its code should implement the thread's running behavior. • The first thread to be executed in a multithreaded process is called the main thread. • The main thread is created automatically on the start up of Java program execution. MainThread.java
Life Cycle of a Thread • The various states in the life cycle of a thread are: • New • Runnable • Not Runnable • Terminated or Dead
States of Thread • New • A thread object that is newly created. Syntax: • Runnable: • When the start method of thread is invoked, the JVM calls the run method. • Now the thread is ready to execute but not allocated to the processor, because the processor may be busy with another operation. Thread newThread = new Thread(this,”threadName”);
States of Thread – Contd., • Not Runnable: Sleep: • When the sleep method of Thread class is called, the thread goes to the sleep state. When the time specified in the sleep method elapses, then the thread moves to runnable state. Wait: • When the wait method is called, the thread goes to the wait state. It moves to runnable state when it is notified by another thread or time specified in the wait method elapses.
States of Thread – Contd., • Blocked • When a thread is waiting for any I/O operations, it transitions to the blocked state. When the required resource is available, then it moves to runnable state. • Dead • When the thread completes execution, it transitions to the dead state.
Creating Threads • There are two ways to create thread in java: • Implement the Runnable interface (java.lang.Runnable) • By Extending the Thread class (java.lang.Thread) The Runnable Interface Signature public interface Runnable { void run(); }
Creating Threads – Contd., • Extending Thread Class Public Class ThreadDemo extends Thread { Public void run() { //Task for thread defined. } }
Runnable Interface vs Thread Class When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class: • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interfacehas this option. • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be expensive. Runnable Interface Demo Extending ThreadClass Demo Creating MultipleThreads Demo
Thread Priorities • In Java we can specify the priority of each thread relative to other threads. Those threads having higher priority get greater access to available resources then lower priority threads. • The following static final integer constants are defined in the Thread class:
Thread Priorities – Contd., • The priority of an individual thread can be set to any integer value between and including the above defined constants. • Thread’s priority can be modified any time after its creation using the setPriority() method and its priority value can be retrieved using getPriority() method. • When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.
Thread Priorities – Contd., • If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true: • A higher priority thread becomes Runnable. (Pre-emptive scheduling) • It yields, or its run() method exits on systems that support time-slicing, its time allotment has expired ThreadPriorityDemo
Thread Synchronization • “ With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.” • In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. • Synchronization prevents such typeof data corruption which may otherwise lead to dirty reads and significant errors.
Thread Synchronization – Contd., • Synchronization is based on the concept of monitor. • The monitor controls the way in which synchronized methods access an object or class. • To enter an object’s monitor, you need to call a synchronized method or synchronized block. • When a thread calls the wait() method, it temporarily releases the locks that it holds. In addition, the thread stops running and is added to the list of waiting threads for that object.
Thread Synchronization – Contd., • Synchronization is achieved using synchronized key word • Synchronization is achieved in two ways: • Syncronized methods • Synchronized blocks
Synchronized Methods “ Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. “ • Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. • A synchronized method can only use “this” current object.
Synchronized Methods – Contd., Example: public synchronized void add(int value) { this.count += value; } SynchronizationMethodDemo
Synchronized Blocks • synchronized block you may lock on an object other than “this” which allows to be much more flexible. • Example: public void add(int value){ Student s=new Student(); synchronized(s) { this.count += value; } } SynchronizationBlockDemo
Inter-Thread Communication • Communication between threads is known as Interthreaded communication. • Java provides well designed inter-process mechanism using the wait(), notify() and notifyAll() methods. • wait() tells the calling thread to exit and enter the ‘sleep’ state till some other thread enters and calls notify() • public final void wait() throws InterruptedException • public final notify() • notifyAll() wakes up or notifies all the threads that called wait( Joining Threads: A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
Wait-Notify Mechanism notify( ) First thread notify( ) wakes up or notifies the first thread. notifyAll( ) wakes up or notifies all the threads that called wait( ) on the same object. notifyAll( ) Thread 2 Thread 3 Thread 1 JoinDemo InterThreadCommDemo(Producer Consumer.java)
Summary • A thread is defined as the path of execution of a program. It is a sequence of instructions that is executed to define a unique flow of control. • A program that creates two or more threads is called a multithreaded program. • The two types of multitasking are: • Process-based • Thread-based • The java.lang.Thread class is used to construct and access individual threads in a multithreaded application.
Summary – Contd., • The various advantages of multithreading are: • Improved Performance • Minimized System Resources Usage • Simultaneous access to multiple applications • The various states in the life cycle of a thread are: • New • Runnable • Not Runnable • Terminated or Dead • You can create a thread in the following ways: • Implementing Runnable interface • Extending the Thread class
Summary – Contd., • Thread priorities are the integers in the range of 1 to 10 that specify the priority of one thread with respect to the priority of another thread. • You can set the thread priority after it is created using the setPriority() method declared in the Thread class. • Synchronization of threads ensures that if two or more threads need to access a shared resource, the resource is used by only one thread at a time. • Various threads can communicate with each other using the following methods: • wait() • notify() • notifyAll()
References • http://www.cs.bris.ac.uk/Teaching/Resources/MR09/lectures/mk2/img20.htm