THREADS
A Process is a program in execution.
Two or more processes are running
concurrently in a computer is called
multitasking.
Java provides support for multithreading.
Multithreading threading environment , tasks
are known as threads.
Threads share the same address space and
cooperatively share the same heavy weight
process.
2
THREADS
A Process is a program in execution.
Two or more processes are running
concurrently in a computer is called
multitasking.
Java provides support for multithreading.
Multithreading threading environment , tasks
are known as threads.
Threads share the same address space and
cooperatively share the same heavy weight
process.
3
Definition:
A thread is a line of execution. It is the
smallest unit of code that is dispatched by
the scheduler. Thus a process can contain
multiple threads to execute its different
sections. This is called multithreading.
Single threaded process: A process is made
up of one thread is known as single threaded
process.
Multithreaded Process: A process that
creates two or more threadsis called a
multithreaded process.
4
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.
Multithreading is a specialized form of
multitasking.
Many problems solved concurrently.
5
Improved performance
Minimized system resource usage
Simultaneous access to multiple applications
Program structure simplification
Types of multitasking:
Multitasking is theability to execute
more than one task at the same. It can
be divided into two categories:
process-based
thread-based
6
7
Threads exist in several states. They
are:
Newborn state
Runnable state
Running state
Blocked state
Dead state
A Thread is always in one of these five
states.
8
Whenwecreateathreadobject,the
threadisbornandissaidtobeinnewborn
state.Atthisstate,wecandoonlyoneof
thefollowingthings:
(i) Schedule it for running using start() method
(ii) Kill it using stop() method
9
Start()-Thestartmethodstartsexecution
oftheinvokingobject.Itcanthrowan
IllegalThreadStateExceptionifthethread
wasalreadystarted.
Stop()–Thismethodterminatestheinvoking
object.
Suspend()–Themethodsuspendsthe
invokingobject.Thethreadwillbecome
runnableagainifitgetstheresume()
method.
Sleep()–Thismethodsuspendsexecutionof
theexecutingthreadforthespecified
numberofmilliseconds.Itcanthrowan
InterruptedException. 17
A running thread ends its life when it has completed executing its run() method or we can kill it by sending the stop message.
class CurrentThreadDemo {
public static void main(String args[ ])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
21
1. sleep( ) :
It causes the thread from which it is called
to suspend execution for the specified period
of milliseconds and also in nanoseconds.
static void sleep(long milliseconds) throws
InterruptedException
static void sleep(long milliseconds, int
nanoseconds) throws InterruptedException
2. setName( ):
To set the name of a thread.
final void setName(String threadName)
25
3. getName( ):
To obtain the name of a thread
final String getName( )
threadNamespecifiesthenameofthe
thread.
TheThreadclassdefinesseveralmethods
thathelpmanagethreads.
26
Method Meaning
getName() Obtain a thread’s
name.
setName(String) Sets the thread name
getPriority() Obtain a thread’s
priority.
isAlive() Determine if a thread
is still running.
27
Join() -Wait for a thread to
terminate.
run -Entry point for the thread.
sleep -Suspend a thread for a
period of time (ms).
start -Start a thread by calling its
run method.
28
class CreateThreadDemo
{
public static void main(String args[ ]){
new NewThread(); // create a new
thread
try
{
for(int k = 10; k > 6; k--) {
System.out.println("Parent Thread: " +k);
Thread.sleep(1000);
} }
37
To determine whether a thread has finished.
final boolean isAlive( )
It returns true if the thread upon which it is
called is still running, otherwise returns
false.
The method used to wait for a thread to
finish is called join( ),
final void join( ) throws
InterruptedException
This method waits until the thread on which
it is called terminates.
42
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
43
public void run()
{
try {
for(int i = 3; i > 0; i--)
{
System.out.println(name + ": " + i)
Thread.sleep(1000);
}
}
44
System.out.println("Thread 1 is
alive:"+ob1.t.isAlive());
System.out.println("Thread 2 is
alive:"+ob2.t.isAlive());
System.out.println("Thread 3 is
alive:"+ob3.t.isAlive());
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
46
catch (InterruptedExceptione)
{
System.out.println("Main thread
Interrupted"); }
System.out.println("Thread 1 is
alive:"+ob1.t.isAlive());
System.out.println("Thread 2 is
alive:"+ob2.t.isAlive());
System.out.println("Thread 3 is
alive:"+ob3.t.isAlive());
System.out.println("Main thread
Exiting");
}
}
47
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 3
Two: 3
Thread 1 is alive:true
Thread 2 is alive:true
Thread 3 is alive:true
Three: 3
One: 2
Two: 2
Three: 2
48
Three: 1
One: 1
Two: 1
Three exiting.
One exiting.
Two exiting.
Thread 1 is alive: false
Thread 2 is alive: false
Thread 3 is alive: false
Main thread Exiting
49
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.
• MIN_PRIORITY =1
• MAX_PRIORITY = 10
• NORM_PRIORITY = 5 (default priority)
51
class Counter implements Runnable
{
Thread thread;
intcounter = 0;
volatile booleangoflag; // volatile –its value
can be changed by another thread
public Counter(intp)
{
thread = new Thread(this);
thread.setPriority(p);
}
52
public void start()
{ goflag= true;
thread.start();
}
public void run()
{ while (goflag)
counter++;
}
public void end()
{ goflag= false;
}
}
53
class PriorityDemo{
public static void main(String args[])
{
Counter thread1= new Counter
(Thread.NORM_PRIORITY+ 2);
Counter thread2 = new Counter
(Thread.NORM_PRIORITY+ 1);
Counter thread3 = new Counter
(Thread.NORM_PRIORITY-1);
Counter thread4 = new Counter
(Thread.NORM_PRIORITY-2);
54
class SynchronizeDemo1
{
public static void main(String args[ ])
{
Shared shared= new Shared();
CustomThreadthread1 = new
CustomThread(shared, "one");
CustomThreadthread2 = new
CustomThread(shared, "two");
CustomThreadthread3 = new
CustomThread(shared, "three");
CustomThreadthread4 = new
CustomThread(shared, "four");
59