Thread
Thread
in Java
Threads
• A lightweight sequential flow of control that
shares an address space and resources with
other threads.
• A process consists of one or more threads, the
code, data and other resources of program in
memory.
• A thread consists of a stack, the state of CPU
registers and an entry in the execution list of
system scheduler.
• A thread, unlike processes (heavyweight), has
a low context switching time.
• Threads are compulsory for sockets, image
holding, and animation.
Purpose of Threads
• To maintain responsiveness of an application
during a long running task.
• To enable cancellation of separable tasks.
• Some problems are parallel.
• To monitor status of some resource (DB).
• Some APIs and systems demand it: Swing.
• To take advantage of multiple processors.
• It looks great on your resume.
How to create threads
• There are two ways of creating threads in
Java:
1) Extend the “Thread” class
We can instantiate the class Thread as many
times as desired to achieve multi-threading.
2) Implement the “Runnable” interface
Since multiple inheritance is not allowed in Java,
this method is used when the program already
extends another class (Ex. Applets)
Threads and Processes
CPU
main
run
Process 1 Process 2 Process 3 Process 4
GC
1) Extend the Thread class
• Create a subclass of java.lang.Thread:
public class MyThread extends Thread {
public void run() { \\put code here
}
}
• Instantiate MyThread:
MyThread myTrd;
myTrd.start(); // calls run() in MyThread
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);
try
{
for (int n=5;n>0 ;n-- )
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
Result
---------- Run ----------
Current Thread:Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
start()
New
New Thread
Thread Runnable Not
Not Runnable
Runnable
run() terminates
Dead
Dead
In and Out of Runnable
Out of Runnable Back to Runnable
• sleep() is invoked. • Specified number of
milliseconds elapsed.
• wait() is invoked (for a • An object notifies the
specified condition to waiting thread that the
be satisfied). condition is satisfied.
• Thread is blocked on • I/O event the thread is
I/O. blocked on, is
completed.
Thread Life Cycle
sleep
Done
sleeping
new start
blocked
suspend resume
wait notify
runnable
Block
on I/O
I/O
complete
stop
dead
Class Thread Priorities
• The class Thread has three fields:
– MAX_PRIORITY
– MIN_PRIORITY
– NORM_PRIORITY: the default priority
assigned to a thread
isAlive & join methods
• Normally, we want to finish main thread in last.
• This task done by calling sleep() within main() with a long
enough delay.
• Its difficult to know that when will be another thread
ended.
• Both method determine whether a thread has finished.
• isAlive method returns a Boolean value regarding to
thread.
• Join method waits until the thread on which its called
terminates.
Synchronization
The objective of synchronization is to make
sure that when several threads need access
to a shared resource, only one thread can
access it at any given time.
Use synchronized at the
– method level: declare methods to be
synchronized
– block of code level: declare some code to be
synchronized
public void run()
{
synchronized(target)
{
target.call(msg);
}
class Callme {
void call(String msg) {
System.out.print("["+msg);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}