Sei sulla pagina 1di 15

11 INTRODUCTION TO THREADS

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.

class HelloThread extends Thread


{
public void run()
{ try{
for ( ; ; )
{
System.out.println("hello");
sleep(1000);
} }catch(Exception e){}
} } public class ThreadTest
{
public static void main(String[] args) throws
Exception
{
Thread hello = new HelloThread();
hello.start();

Page 4
11 INTRODUCTION TO THREADS

System.out.println("Sorry, I must be leaving");


} }

Output

1.2 Threaded Applications


A thread is a process in execution within a program. Within a program each thread defines a
separate path of execution. A process contains multiple threads that executes according to
program code. Multiple threads are used to do a work in parallel.

Benefits of using threads:


- It allows to perform more than one task at a time.
- Resource sharing between threads is easy.
- It maximizes CPU utilization
- It reduces the complexity of large programs.
- It increases the speed of execution.

1.3 Creating Threads


There are two methods to create threads. They are
i) Creating threads by extending Thread class.
ii) Creating threads by implementing Runnable interface

Page 5
11 INTRODUCTION TO THREADS

Creating threads by extending Thread class


The steps given below are used to create a thread by extending thread class.
Define a thread subclass by extending from the super class thread.
Override the thread class method run() in the extended class with the statements
to be executed by the thread.
Write the main class and define thread objects.
Using the created thread objects start the thread using start() method.

i) Creating threads by implementing runnable interface


The steps given below are used to create a thread by implementing runnable interface
Define a thread subclass by implementing from the interface Runnable
Declare the thread class method run() in the implemented class with the
statements to be executed by the thread.
Write the main class and define thread objects.
Use the created thread object as the argument to the constructor Thread and
start the thread.
1.4 Thread states
The status of a thread is provided by the thread state property. Because threads can be in
more than one state at any given time, the value stored in Thread State can be a
combination of the values in the thread state enumeration.
Thread methods
The important thread class methods are
a) run()
This method should be overridden in our thread extended the superclass thread. This
method contains the statements for the particular thread.

public void run(){


statements
}

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()

1.5 Co-coordinating threads

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;

public class Coordinate{


public static void main(String[] args) throws
Exception {
int threads = 3;
final CountDownLatch startLatch = new
CountDownLatch(threads);
final CountDownLatch endLatch = new
CountDownLatch(threads);
ExecutorService svc =
Executors.newFixedThreadPool(threads);

Page 8
11 INTRODUCTION TO THREADS

for (int i = 0; i < threads; i++) {


svc.execute(new Runnable() {
public void run() {
try {
log("During run()");
startLatch.countDown();
startLatch.await();
log("Do the work Now");
Thread.sleep((int) (Math.random() * 1000));
log("Waiting for end");
endLatch.countDown();
endLatch.await();
log("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Thread.sleep(100); } }
private static void log(String msg) {
System.out.println(System.currentTimeMillis() + ": "
+ Thread.currentThread().getId() + " " + msg);
}
}

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

public class Threads{


public static void main(String[] args){
Thread th = new Thread();
System.out.println("Numbers are printing line by line
after 5 seconds : ");
try{
for(int i = 1;i <= 10;i++)

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

c) when wait() is called


d) when suspend() is called
The graph given below shows the flow of running state of the thread.

Blocked state

suspend() sleep() wait()


Newborn Run mode Running Dead 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

Newborn Run Running Dead state


mode

Sleep()

Yield()
Suspend() Wait()

wait()
Blocked state

Page 12
11 INTRODUCTION TO THREADS

Dead State

A thread is said to be in dead state if any one of the following happens

a) if it completes its execution


b) If it is called by the method stop()
The graph given below shows the complete life cycle of a thread
Stop()

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

final void setPriority(int level)

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.

The general form to call the setPriority() method is


Threadobject.setPriority(int level);

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

class MyThread1 extends Thread{


MyThread1(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();

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");
}
}

1.7 Thread Synchronization


Synchronization is a technique to overcome the problems which arise when more than one
thread tries to access a particular resource.

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().

1.8 Runnable Interface


Runnable is a thread interface. By implementing this we can create new threads. The steps
to be followed to create a new thread class is,

a) Create thread subclasses by implementing the interface Runnable.

class Newthread implements Runnable


{
..
..
}

b) Define the method run() in all implemented class with the corresponding statements as
shown below.

Page 16
11 INTRODUCTION TO THREADS

Public void run()


{

.
}
c) Write the main class and define thread objects for the created threads.
d) Start the newly created thread by using the method start(). The general form is,

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

Potrebbero piacerti anche