0% found this document useful (0 votes)
21 views24 pages

Thread

Uploaded by

yodala159
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views24 pages

Thread

Uploaded by

yodala159
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 24

Threads

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

Output completed (5 sec consumed) - Normal Termination


class NewThread extends Thread
{
NewThread()
{
super("Demo Thread");
System.out.println("Child thread:"+this);
start();
}
public void run()
{
try
{
for (int i=5;i>0 ;i-- )
{
System.out.println("Child Thread:"+i);
Thread.sleep(500);
}
}
catch (InterruptedException e){
System.out.println("Exiting child thread");
}
}
class ExtendedThread
{
public static void main(String args[])
{
new NewThread();
try
{
for (int i=5;i>0 ;i-- )
{
System.out.println("Main Thread:" +i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted:");
}
System.out.println("Main thread exiting");
}
}
Result
---------- Run ----------
Child thread:Thread[Demo Thread,5,main]
Main Thread:5
Child Thread:5
Child Thread:4
Main Thread:4
Child Thread:3
Child Thread:2
Main Thread:3
Child Thread:1
Main Thread:2
Main Thread:1
Main thread exiting

Output completed (5 sec consumed) - Normal Termination


Methods in Class Thread
• Three primary methods to control a thread:
– public native synchronized void start()
prepares a thread to run
– public void run()
actually performs the work of the thread
– public final void stop()
to terminate the thread. The thread also dies
when run() terminates.
start() & run() in Thread
• start() causes the thread to begin execution
and the Java Virtual Machine calls run().
Thus, we never have to call run() explicitly.
• The result is that two threads are running
concurrently: the current thread which
returns from the call to start() and the thread
that executes run().
Other Methods in Thread
• Other important methods in Thread include:
– suspend() and resume()
– sleep(mls) which causes the thread to
temporarily stop execution for mls milliseconds
– getName() and getPriority()
2) Creating a thread by using
Runnable Interface
• Instantiate Thread and pass it “this” (the
applet) as a parameter.
• Use the method start() to start running the
instantiated thread.
• Place all the important code for the
instantiated thread in the run() method.
• Set the instantiated thread to “null” in the
stop() method.
Implement Runnable interface
• Create a class that implements Runnable:
public class MyFoo extends Applet
implements Runnable;
• Runnable is an interface in java.lang that
contains only one method: run().
• Multiple inheritance is not allowed in Java,
thus this method of creating threads is used
when MyFoo already extends another class.
The Life Cycle of a Thread
running

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

You might also like