Module 5 Java1 (1)
Module 5 Java1 (1)
Module 5 Java1 (1)
MODULE 5
Chapter-1
Multi-Threaded Programming:
The Java Thread Model,
The Main Thread,
Creating a Thread,
Creating Multiple Threads,
MULTI- Using isAlive() and join(),
THREADED Thread Priorities,
Synchronization,
PROGRAMMING Interthread Communication,
Suspending, Resuming, and Stopping Threads,
and Obtaining a Thread’s State.
ENUMERATIONS, Enumerations, Type Wrappers and Autoboxing
Enumerations (Enumeration Fundamentals, The
TYPE WRAPPERS AND
values() and valueOf() Methods),
AUTOBOXING: Type Wrappers (Character, Boolean, The Numeric
Type Wrappers),
Autoboxing (Autoboxing and Methods,
Autoboxing/Unboxing Occurs in Expressions,
Autoboxing/Unboxing Boolean and Character
Values).
1
MODULE-5 MULTITHREADED PROGRAMMING
Multi-Threaded Programming
Multithreading in Java is a process of executing multiple threads simultaneously for
maximum utilization of CPU.
Each part of such a program is called a thread.
Multithreading is used to achieve multitasking.
There are two distinct types of multitasking:
Process based multitasking.
Thread-based multitasking.
Process-based multitasking (Multiprocessing):
Process-based multitasking is to run two or more programs concurrently
Each process has an address in memory. In other words, each processallocates
a separate memory area.
Thread-based multitasking (Multithreading):
In thread-based multitasking, a single program can perform two or more tasks
simultaneously.
Threads share the same address space.
New:
The thread is in new state if you create an instance of Thread class but before the
invocation ofstart() method.
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
2
MODULE-5 MULTITHREADED PROGRAMMING
WAITING:
A thread enters this state if it waits to be notified by another thread, which is the result of
calling Object.wait( ) or Thread.join( ).
The thread also enters waiting state if it waits for a Lock or Condition in the
java.util.concurrent package.
When another thread calls Objects notify()/notifyAll() or Condition‟s signal()/signalAll(),
the thread comes back to the runnable state.
Timed-Waiting
A thread enters this state if a method with timeout parameter is called: sleep(), wait(),
join(), Lock.tryLock() and Condition.await(). The thread exits this state if the timeout
expires or the appropriate notification has been received.
Terminated
A thread enters terminated state when it has completed execution. The thread terminates
for one of two reasons:
o The run( ) method exits normally.
o The run() method exits abruptly due to a uncaught exception occurs.
As we create Main Method in each and every Java Program, which acts as an entry point for the code to get
executed by JVM.
Similarly in this Multithreading Concept, Each Program has one Main Thread which was provided by default
by JVM, hence whenever a program is being created in java.
3
MODULE-5 MULTITHREADED PROGRAMMING
There are certain properties associated with the main thread which are as follows:
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
Example
1. import :
java.util.*;
2. public class MainThreadExample
3. {
4. public static void main(String[] args)
{
5. Thread t=new thread();
System.out.println("Start of main thread, current thread is" +t);
t.setName(“mythread”);
System.out.println(“after the change: “+t);
6. try
{
for(int i=5;i>0;i--)
{
System.out.println(i);
7. Thread.sleep(1000); // in milliseconds
}
}
catch (InterruptedException e)
{
System.out.println(“main thread interrupted”);
}
} 4
}
MODULE-5 MULTITHREADED PROGRAMMING
Output:
Start of main thread, current thread is Thread[main,5,main]
After the change: Thread[mythread,5,main]
5
MODULE-5 MULTITHREADED PROGRAMMING
isAlive() function
Join() method
java.lang.Thread class provides the join() method which allows one thread to wait until another
thread completes its execution.
7
MODULE-5 MULTITHREADED PROGRAMMING
If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is
terminated before the next instruction is executed by the program.
If there are multiple threads calling the join() methods that means overloading on join allows the
programmer to specify a waiting period.
However join is dependent on the OS for timing, so you should not assume that join will wait
exactly as long as you specify.
There are three overloaded join functions.
1. join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is
interrupted then it will throw InterruptedException.
Syntax:
public final void join()
2. join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or
wait for specified time (milliseconds).
Syntax:
public final synchronized void join(long millis)
3. join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called
is dead or wait for specified time (milliseconds + nanos).
4. Syntax:
public final synchronized void join(long millis, int nanos)
Example 1
1. import java.io.*;
2. // The ThreadJoin class is the child class of the class Thread
3. class ThreadJoin extends Thread
4. {
public void run() // overriding the run method
{
for (int j = 0; j < 2; j++)
{
try
{
5. // sleeping the thread for 300 milli seconds
Thread.sleep(300);
System.out.println("The current thread name is: " + Thread.currentThread().getName());
}
6. // catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught: " + e);
}
System.out.println( j );
}
8
}
7. }
MODULE-5 MULTITHREADED PROGRAMMING
9
MODULE-5 MULTITHREADED PROGRAMMING
Output:
The current thread name is: main
The current thread name is: Thread - 0 Explanation: The above program shows that the
0 second thread th2 begins after the first thread th1
The current thread name is: Thread - 0 has ended, and the thread th3 starts its work after
1
The current thread name is: main the second thread th2 has ended or died.
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1
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). Amonitor is an
object that is used as a mutually exclusive lock, or mutex.
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 re enter
the same monitor if it so desires.
Let us try to understand the problem without synchronization. Here, in the following example to
threads are accessing the same resource (object) to print the Table. The Table class contains one
method, printTable(int ), which actually prints the table. We are creating two Threads, Thread1 and
Thread2, which are using the same instance of the Table Resource (object), to print the table. When
one thread is using the resource, no other thread is allowed to access the same resource Table to print
the table.
void printTable(int n)
{ //method not synchronized
for(int i=1;i<=5;i++)
{
10
MODULE-5 MULTITHREADED PROGRAMMING
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println("The Exception is :"+ie);
}
}
} //end of the printTable() method
}
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
11
MODULE-5 MULTITHREADED PROGRAMMING
where synchronized is the keyword, method contains the type, and method_name represents the
name of the method, and para_list indicate the list of the parameters.
Class Table
{
Thread.sleep(400);
}
catch(InterruptedException ie)
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
13
MODULE-5 MULTITHREADED PROGRAMMING
Output: 5
10
15
20
25
100
200
300
400
500
In the above output it can be observed that when Thread1 is accessing the Table object, Thread2 is not
allowed to access it. Thread1 preempts the Thread2 from accessing the printTable() method.
Note:
This way of communications between the threads competing for same resource is
called implicit communication.
This has one disadvantage due to polling. The polling wastes the CPU time. To save
the CPU time, it is preferred to go to the inter-thread communication.
Example-2
package jk;
t1.start();
t2.start();
}
}
14
MODULE-5 MULTITHREADED PROGRAMMING
package jk;
package jk;
package jk;
Without Thread Synchronization (Random output with both threads – we will getdifferent outputs with
different runs)
11 51 51
51 11 11
52 52 52
12 12 12
53 13 53
13 53 13
15
MODULE-5 MULTITHREADED PROGRAMMING
54 54 14
14 14 54
55 55 15
15 15 55
With Thread Synchronization (Always gets same output that is Thread1 followed byThread2)
11
12
13
14
15
51
52
53
54
Thread Priorities
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. In practice, the
amount of CPU time that a thread gets often depends on several factors besides its priority. A
higher-priority thread can also preempt a lower-priority one.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
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.
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
Example Program:
17
MODULE-5 MULTITHREADED PROGRAMMING
Inter-Thread Communication
If two or more Threads are communicating with each other, it is called "inter thread"
communication.
Using the synchronized method, two or more threads can communicate indirectly.
Through, synchronized method, each thread always competes for the resource. This way of
competing is called polling(In polling client send requests to server at intervals to check the
status of a running job.).
The polling wastes the much of the CPU valuable time. The better solution to this problem is, just
notify other threads for the resource, when the current thread has finished its task. This is explicit
communication between the threads.
Java addresses this polling problem, using via 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( ) 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 a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.
18
MODULE-5 MULTITHREADED PROGRAMMING
19
// Create another thread object that calls // pc.consume()
MODULE-5 MULTITHREADED PROGRAMMING
Thread t2 = new Thread(new Runnable());
{
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
t1.start();// Start both threads
t2.start();
t1.join();// t1 finishes before t2
t2.join();
}
wait();// releases the lock on shared resource // and waits till some other method invokes notify().
System.out.println("Resumed");
}
}
// Sleeps for some time and waits for a key press. After key // is pressed, it notifies produce().
Thread.sleep(2000); // Sleep
} 20
}
MODULE-5 MULTITHREADED PROGRAMMING
Explanation:
1. In the main class, a new PC object is created.
2. It runs produce and consume methods of PC objects using two different threads, namely t1 and t2, and
waits for these threads to finish.
Let’s understand how our produce and consume method works.
The use of a synchronized block ensures that only one thread at a time runs. Also, since there is a sleep
method just at the beginning of consume loop, the producing thread gets a start.
When the wait is called in produce method, it does two things. Firstly it releases the lock it holds on the
PC object. Secondly, it makes the produce thread go on a waiting state until all other threads have
terminated. It can again acquire a lock on a PC object, and some other method wakes it up by i nvoking
notify or notifyAll on the same object.
Therefore we see that as soon as the wait is called, the control transfers to consume thread, and it prints
-“Waiting for return key.”
After we press the return key, consume method invokes notify(). It also does two things- Firstly, unlike
wait(), it does not release the lock on shared resources therefore for getting the desired result, it is
advised to use notify only at the end of your method. Secondly, it notifies the waiting threads that they
can now wake up but only after the current method terminates.
As you might have observed that even after notifying, the control does not immediately pass over to the
produce thread. The reason for it is that we have called Thread.sleep() after notify(). We already know
that the consume thread is holding a lock on a PC object. Another thread cannot access it until it has
released the lock. Hence only after the consume thread finishes its sleep time and after that terminates
by itself, the produce thread cannot take back the control.
After a 2 second pause, the program terminates to its completion.
Whenever we want stop a thread we can stop from running using "stop()" method of thread
class. It's general form will be as follows:
Thread.stop();
This method causes a thread to move from running to dead state. A thread will also move
to dead state automatically when it reaches the end of its method.
Blocking Thread
A thread can be temporarily suspended or blocked from entering into the runnable and running
state by using the following methods:
21
MODULE-5 MULTITHREADED PROGRAMMING
Example program:
// Using suspend() and resume().
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
getState() method
The getState() method of the Thread class is an instance method that returns the state of the
thread object on which this method is invoked.
Syntax
Parameters
The method has no parameters.
Return value
This method returns an enum State that has the following values:
23