Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1. Introduction to Threads
1.1 Non Threaded Applications
A process is a collection of instructions which are executed simultaneously at the runtime. A
thread is a process which exists within a program and it is executed to perform a particular
task. A single process consists of several threads. A process is associated with several
threads of execution.
When the thread runs, the process ends at a time. But in non threaded applications the
process runs continuously. In java any thread can be a daemon thread. Daemon threads are
service providers for other threads running in the same process as the daemon thread. If
normal threads are not running & remaining threads are daemon threads then the
interpreter exits.
Example program
The following program illustrates the non-threading application.
Page 4
11 INTRODUCTION TO THREADS
Output
Page 5
11 INTRODUCTION TO THREADS
Page 6
11 INTRODUCTION TO THREADS
b) start()
his method is used to start the run() method. If the method is already started it throws
illegal Thread state exception. The general form is
void start()
c) sleep()
This method is used to block the currently executing thread. The general form is
static void sleep(longint a)
where
a- integer value. This gives the time for sleeping in milli seconds
d) interrupt()
This method is used to interrupt the currently running thread. The general form is
void interrupt()
e) interrupted()
The general form is
static boolean interrupted()
This method returns true, if the current thread is interrupted else false.
f) isAlive()
This method is used to check whether the thread is running or not. The general form is
Boolean isActive()
This method returns true, if the thread is running else false.
g) stop()
This method is used to stop the running thread. The general form is
void stop()
h) yield()
This method is used to bring the stopped thread to run mode. The general form is
void yield()
Page 7
11 INTRODUCTION TO THREADS
i) wait()
This method is used to stop the currently running thread. The general form is
void wait()
Java has several new features such as concurrency primitives and collections. There are two
classes that can be used to co-ordinate threads. They are
i. CountDownLatch
ii. CyclicBarrier.
A CountDownLatch is initialized with a counter. Threads can then either count down on the
latch or wait for it to reach 0. When the latch reaches 0, all waiting threads are released.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
Page 8
11 INTRODUCTION TO THREADS
In the above program two latches get initialized. Each thread will start up count down on
the latch and will wait for the latch counting down to zero (when all threads have been
initialized).
Page 9
11 INTRODUCTION TO THREADS
Output
Here the run() method is called several times, but proceeds the barrier at the same time.
They all wait for the latch and then proceed together. Each count down latch can only be
used once and it is then dead.
If we need set of threads to repeatedly meet at a common point we can use the cyclic
barrier.
1.6 Interrupting Methods
An interrupt is an indication to a thread that it should stop what it is doing and do
something else.
How does a thread support its own interruption? This depends on what it's currently doing.
If the thread is frequently invoking methods that throw Interrupted Exception, it simply
returns from the run method after it catches that exception.
Example for interrupting threads
Page 10
11 INTRODUCTION TO THREADS
{
System.out.println(i);
th.sleep(5000);
}
}
catch(InterruptedException e){
System.out.println("Thread interrupted!");
e.printStackTrace();
} }}
Output
Running state:
If a thread is in execution then this state is called running state. This state continues until
any one of the following happens after the completion of the execution
a) when yield() is called
b) when sleep() is called
Page 11
11 INTRODUCTION TO THREADS
Blocked state
stop() or completed
Blocked state:
A thread becomes blocked state if any one of the following method is called while thread is
running.
a) sleep()
b) wait()
c) suspend()
From blocked state it comes to run mode state if the yield () method is called. The graph
given below shows the flow of the blocked state of the thread.
Stop() or completed
Sleep()
Yield()
Suspend() Wait()
wait()
Blocked state
Page 12
11 INTRODUCTION TO THREADS
Dead State
New Run
Running Dead state
born mode
Blocked state
Thread Priority
Priority is an integer value assigned to every thread by the o/s. According to this value the
threads are given CPU for execution. Normally O/S assigns same priority value to the
created threads. So the created threads share priority value to the created threads. So the
created threads share the cpu in first come first serve basis (FCFS).
But in java there is a facility to set the priority of the threads by the user. This is done with
the help of the method setPriority() available in the Thread class. The general form is
where
final,void -keywords
setPriority -method
level -priority level
Page 13
11 INTRODUCTION TO THREADS
The value of priority level should be between the predefined value MIN_PRIORITY. The
default values are,
MIN_PRIORITY=1
MAX_PRIORITY=10
In addition there is another predefined priority called as NORM_PRIORITY and its default
value is 5. Java by default takes the NORM_PRIORITY value.
Where
Thread object - already created thread object
Level - integer value to give the priority
Finding the priority of the thread
The user can find the priority of the thread by using the method getPriority() which is
available in the Thread class. The general form is,
final int getPriority();
Example program
Page 14
11 INTRODUCTION TO THREADS
System.out.println("Thread Name
:"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
} }}
class MyThread2 extends Thread{
MyThread2(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name
:"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
} }}
public class Setpriority{
public static void main(String args[]){
MyThread1 m1=new MyThread1("My Thread 1");
MyThread2 m2=new MyThread2("My Thread 2");
}
}
Page 15
11 INTRODUCTION TO THREADS
Principle
At the time of synchronization, java creates a monitor for the thread which calls the
resource first and hands it over to it.The thread which has the monitor can only access the
resource. So all other threads are not allowed to access the resource.
If the keyword synchronized is given in front of a method, then that method becomes
synchronized method, so it does not allow other threads to access it when one thread is
accessing it.
Example program
synchronized void display(int m)
{
for(int i;i<=m;i++)
{
System.out.println("i="+i);}}
Let us consider three objects o1,o2,o3. Assume that o1 is accessing the synchronized
method display().
During this time the other objects o2 & o3 are not allowed to access it. Only after o1
completes accessing either o1 or o3 get chance to access the method display().
b) Define the method run() in all implemented class with the corresponding statements as
shown below.
Page 16
11 INTRODUCTION TO THREADS
t1=new Newthread();
new Thread(t1).start();
Example program
RunBasicThread(char c) {
this.c = c;
}
// override run() method in interface
public void run() {
for(int i=0; i<100; i++) {
System.out.print(c);
try{
Thread.sleep((int)(Math.random() * 10));
} catch( InterruptedException e ) {
System.out.println("Interrupted Exception
caught");
} }}
public static void main(String[] args) {
RunBasicThread bt = new RunBasicThread('!');
RunBasicThread bt1 = new RunBasicThread('*');
// start RunBasicThread objects as threads
new Thread(bt).start();
new Thread(bt1).start();
}}
Page 17
11 INTRODUCTION TO THREADS
Output
1.9
Thread Groups
Thread Group creates a group of threads. It defines these two constructors:
- ThreadGroup(String groupName)
- ThreadGroup(ThreadGroup parentOb, String groupName)
The group name specifies the name of the thread group. The first one creates a new group
that acts as the parent for the current thread. In the second one the parent is specified as
the parentob. Thread groups offer a convenient way to manage groups of threads as a unit.
This is particularly valuable in situations in which you want to suspend and resume a
number of related threads. The following are the thread groups with their descriptions:
Methods
int activeCount( )
It returns the number of threads in the group plus any groups for which this
thread is a parent.
int activeGroupCount( )
Returns the number of groups for which the invoking thread
is a parent.
final void checkAccess( )
Causes the security manager to verify that the invoking thread may access and/or
change the group on which checkAccess( ) is called
Page 18