module 5 multithreading
module 5 multithreading
UNIT IV
Multithreaded Programming
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.
A thread introduces Asynchronous behaviour.
Multitasking
Two types:
1. Process based multitasking
2. Thread based multitasking
Programs requires separate address spaces Same address space is shared by threads.
Interprocess communication is expensive and Interthread communication is inexpensive.
limited.
Context switching from one process to Context switching from one thread to the next
another is also costly. is lower in cost.
May create more idle time. Reduces the idle time.
Ex: Running a Java compiler and Ex: We can format a text using a Text editor
downloading a file from a web site at the and printing the data at the same time.
same time
The Java Thread Model
The Java run-time system depends on threads for many things, and all the class libraries are
designed with multithreading in mind.
Method Meaning
getName()
getPriority()
setName() Give a name to a thread
setPriority() Set the priority to a thread
isAlive() Determine if a thread is still running.
Join() Wait for a thread to terminate.
Run() Entry point for the thread.
Sleep() Suspend a thread for a period of time.
Start() Start a thread by calling its run method.
currentThread() returns a reference to the thread in which it is called
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Output:
Thread Group:
A thread group is a data structure that controls the state of a collection of threads as a whole.
other class.
The second approach, which employs a Runnable object, is more general, because
the Runnable object can subclass a class other than Thread.
Thread Priorities
1) Every thread has a priority that helps the operating system to determine the order in
which threads are scheduled for execution.
2) Thread priorities are integers that ranges between, 1 to 10.
MIN-PRIORITY (a constant of 1)
3) By default every thread is given a NORM-PRIORITY(5). The main thread always have
NORM-PRIORITY.
4) Context Switch.
Context Switch
Switching from one running thread to the next thread is called as Context Switch.
Rules for Context Switch
1) A thread can voluntarily relinquish control: This is done by explicitly yielding,
sleeping, or blocking on pending I/O. In this scenario, all other threads are examined,
and the highest-priority thread that is ready to run is given the CPU.
Example:
class ThreadDemo implements Runnable
{
public void run()
{
try
{
for(int i=0;i<3;i++)
{
System.out.println("Thread
Demo:"+Thread.currentThread().getName());
Thread.currentThread().sleep(1000);
}
}
catch(InterruptedException ie)
{
System.out.println("Thread interrupted");
}
}
}
class MultiThreadDemo{
public static void main(String ar[])
{
ThreadDemo r = new ThreadDemo();
Thread t1 = new Thread(r);
t1.setName("First Thread");
t1.setPriority(2);
t1.start();
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
We can obtain the current state of a thread by calling the getState( ) method defined by Thread.
Thread.State getState( )
Value State
BLOCKED A thread that has suspended execution because it is waiting to acquire a
lock
NEW A thread that has not begun execution.
RUNNABLE A thread that either is currently executing or will execute when it gains
access to the CPU.
TERMINATED A thread that has completed execution.
TIMED_WAITING A thread that has suspended execution for a specified period of time,
such as when it has called sleep( ). This state is also entered when a
timeout version of wait( ) or join( ) is called.
WAITING A thread that has suspended execution because it is waiting for some
action to occur. For example, it is waiting because of a call to a non-
timeout version of wait( ) or join( ).
Synchronization
Definition:
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.
Process behind Synchronization
Key to synchronization is the concept of the monitor.
A monitor is an object that is used as a mutually exclusive lock.
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.
Synchronizing code
We can synchronize the code in two ways:
1. Using synchronized methods
synchronized void test( )
{
}
2.Using Synchronized statements (synchronized blocks)
synchronized statement
synchronized(objRef) {
// statements to be synchronized
}
Here, objRef is a reference to the object being synchronized
class Account {
private int balance = 50;
public int getBalance()
{
return balance;
}
public void withdraw(int amount)
{
balance = balance - amount;
}
}
class AccountDanger implements Runnable
{
private Account acct = new Account();
System.out.println(Thread.currentThread().getName()+ "
completes the withdrawal");
}
else {
System.out.println("Not enough in account for " +
Thread.currentThread().getName()+ " to withdraw " + acct.getBalance());
}
}
}
public class SyncExample
{
public static void main (String [] args)
{
AccountDanger r = new AccountDanger();
Thread t1 = new Thread(r);
t1.setName("A");
Thread t2 = new Thread(r);
t2.setName("B");
t1.start();
t2.start();
}
}
Output
Interthread Communication
Java includes an elegant interprocess communication mechanism via the wait( ), notify ( ),
and notifyAll( ) methods.
These methods are implemented as final methods in Object, so all classes have them.
All three methods can be called only from within a synchronized context.
wait( ) - 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( ) or notifyAll( ).
notify( ) - notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) - notifyAll( ) wakes up all the threads that called wait( ) on the same object. One
of the threads will be granted access.
Producer produces an item and consumer consumes an item produced by the producer
immediately. Producer should not produce any item until the consumer consumes the item.
Consumer should wait until producer produces a new item.
class Q
{
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q = q;
Thread t = new Thread(this, "Producer");
t.start();
}
public void run()
{
int i = 0;
while(i<10)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
Thread t = new Thread(this, "Consumer");
t.start();
}
public void run()
{
int i = 0;
while(i < 10)
{
q.get();
}
}
}
class PC
{
public static void main(String args[])
{
Q q = new Q();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
}
}
Deadlock
Deadlock describes a situation where two or more threads are blocked forever, waiting
for each other.
Example:
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Suspending, Resuming, and Stopping Threads
Sometimes, suspending execution of a thread is useful.
Example
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 3; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
synchronized void mysuspend() {
suspendFlag = true;
}
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
Byte Streams
Byte streams provide a convenient means for handling input and output of bytes. Byte
streams are used, for example, when reading or writing binary data.
Character Streams
Character streams provide a convenient means for handling input and output of
characters. They use Unicode and, therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byte streams.
Character Stream classes
Character streams are defined by using two class hierarchies. At the top are two
abstract classes: Reader and Writer. These abstract classes handle Unicode character
streams.
Example
applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and executed by Java compatible web browser or
appletviewer.
AppletSkel.java
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
// start or resume execution
System.out.println("START");
}
RunApplet.html
Enumerations
a) An enumeration is a list of named constants.
b) Java enumerations are class types.
c) Each enumeration constant is an object of its enumeration type.
d) Each enumeration constant has its own copy of any instance variables defined by the
enumeration.
e) All enumerations automatically inherit one: java.lang.Enum.
// An enumeration of apple varieties.
enum Apple {
A, B, C, D, E
}
The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants.
Each is implicitly declared as a public, static, final member of Apple.
In the language of Java, these constants are called self-typed.