0% found this document useful (0 votes)
25 views37 pages

Tasks and Multithreading

No, a thread can only be started once. Calling start() on a thread that has already been started will result in an IllegalThreadStateException. The start() method internally calls the run() method of the thread. Once a thread has been started, its run() method will have already executed or be in the process of executing. Calling start() again on the same thread object would cause issues since the run() method can only be executed once per thread. To reuse a thread, you need to either: 1) Create a new thread object 2) Reset/restart the thread by setting its state back to NEW using methods like stop(), suspend(), resume() etc. which are now deprecated.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views37 pages

Tasks and Multithreading

No, a thread can only be started once. Calling start() on a thread that has already been started will result in an IllegalThreadStateException. The start() method internally calls the run() method of the thread. Once a thread has been started, its run() method will have already executed or be in the process of executing. Calling start() again on the same thread object would cause issues since the run() method can only be executed once per thread. To reuse a thread, you need to either: 1) Create a new thread object 2) Reset/restart the thread by setting its state back to NEW using methods like stop(), suspend(), resume() etc. which are now deprecated.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

TASKS AND

MULTITHREAD
ING
LIFECYCLE
OF A
THREAD
STATES OF A THREAD IN
JAVA
Structure
VARIAT • static, dynamic

IONS Level
IN THE • top level tasks only
TASK (flat)
• multilevel (nested)
MODEL Initialization
• with or without
parameter passing
Granularity
• fine or coarse grain
VARIAT
Termination
IONS • natural, suicide
IN THE • abortion, untrapped error
TASK • never, when no longer
needed
MODEL Representation
• fork/join, cobegin, explicit
task declarations
Granularity — coarse (Ada,
Java), fine (occam2)
oamount of work performed by that task
ousually measured in terms of the number
of instructions executed, or
oThe ratio of computation time to
GRANUL communication time
oFine-grained - a program is broken down
ARITY to a large number of small tasks
oCoarse-grained - a program is split into
large tasks
oDiscussion:
oWhat is the impact of granularity to
computation and communication time?
Termination
 completion of execution of the task body;
 suicide, by execution of a self-terminate
statement;
 abortion, through the explicit action of

TERMIN another task;


 occurrence of an untrapped error
ATION condition;
 never: tasks are assumed to be non-
terminating loops;
 when no longer needed.
Hierarchies of tasks can be created
Relationships
 Creation: Parent/Child - the parent may
be delayed while the child is being created
and initialized
NESTED
TASKS  Termination: Guardian/Dependant - a task
may be dependent on the guardian task
itself or on an inner block of the guardian

 The guardian is not allowed to exit from a


block until all dependent tasks of that
block have terminated
A guardian cannot terminate until all its
dependants have terminated
A program cannot terminate until all its
tasks have terminated
A parent of a task may also be its guardian
NESTED (e.g. with languages that allow only static
task structures)
TASKS With dynamic nested task structures, the
parent and the guardian may or may not be
identical
MULTITASKING

The ability of a computer's operating system


to run several programs (or processes)
concurrently on a single CPU. 

Switching from one program to another fast


enough to create the appearance that all
programs are executing simultaneously.
MULTITASKING

Preemptive multitasking Cooperative


multitasking
The operating system decides Each program controls how
how to allocate CPU time slices much CPU time it needs. This
to each program. means that a program must
At the end of a time slice, the cooperate in yielding control to
currently active program is other programs, or else it will
forced to yield control to the hog the CPU.
operating system, whether it
wants to or not.
MULTITHREADING

Allows individual
Multithreading
programs to perform
extends the concept
several tasks
of multitasking.
concurrently.

Each task represents a


Each task is referred
separate flow of
to as a thread.
control.
Example of use
 A web page is taking too long to load in a
web browser, the user could interrupt the
MULTITHRE loading of the page by clicking on the
stop button.
ADING  The user interface can be kept responsive
to the user by using a separate thread for
the network activity needed to load the
page.
THREAD VS PROCESS

Each process has its own Threads share the same


set of variables. data and system resources.

A multithreaded program
must be very careful about
the way that threads access
and modify data, or else
unpredictable behaviour
may occur.
HOW TO CREATE
THREADS IN JAVA

CREATE A SUBCLASS OF THREAD ( WRITE A CLASS THAT IMPLEMENTS


HTTPS://DOCS.ORACLE.COM/JAVASE/7/ THE RUNNABLE INTERFACE.
DOCS/API/JAVA/LANG/THREAD.HTML
).
SUBCLA Create a subclass of the Thread class.
SSING The Thread class has a method named run(),
THE which can be overridden
Implementation of the run() method must
THREAD contain all code that is to be executed within

CLASS the thread.


class MyClass extends Thread {

SUBCLA // ...

SSING
THE public void run() {
// All code to be executed within the
THREAD thread goes here.

CLASS }
}
Create a new thread by instantiating the
SUBCLA class, and we run it by calling the start()
method inherited from class Thread.
SSING Technically OK, conceptually does not
THE make much sense
 MyClass "is a" Thread?
THREAD  We just need a run() method that the Thread

CLASS
class can execute.
SUBCLA
SSING MyClass a = new MyClass();
THE a.start();
THREAD
CLASS
Write a class that implements the
Runnable interface.
The Runnable interface requires us
IMPLEMENTING THE RUNN to implement a single method
ABLE INTERFACE named run(), within which we
place all code that is to be executed
within the thread.
class MyClass implements Runnable
{
// ...

IMPLEMENTING THE RUNN public void run() {


ABLE INTERFACE // All code to be executed
within the thread goes here.
}
}
Create a new thread by creating a
Thread object from an object of
type MyClass.
IMPLEMENTING THE RUNN
ABLE INTERFACE Run the thread by calling the
Thread object's start() method.
MyClass a = new MyClass;
IMPLEMENTING THE RUNN
ABLE INTERFACE Thread t = new Thread(a);
t.start();
String getName()
 Retrieves the name of running thread in the
current context in String format

void start()
THREAD
 This method will start a new thread of
execution by calling run() method of
Thread/runnable object.
METHO void run()
DS IN  This method is the entry point of the thread.
Execution of thread starts from this method.
JAVA void sleep(int sleeptime)
 This method suspends the thread for mentioned
time duration in argument (sleeptime in ms)

void interrupt()
 Interrupts this thread.
void yield()
 By invoking this method the current thread
pause its execution temporarily and allow other
threads to execute.

void join()
THREAD  This method is used to queue up a thread in
execution. Once called on thread, current
METHO thread will wait till calling thread completes its
execution.
DS IN boolean isAlive()
JAVA  This method will check if thread is alive or
dead.

void setPriority(int priority)


 Sets the priority of this thread object. The
possible values are 1~10.
The following methods in the
java.lang.Thread class should no
longer be used, since they can lead to
unpredictable behaviour: stop(),
suspend() and resume().
THREAD • stop() causes a thread to unlock all the
monitors that it has locked. Objects
METHO previously protected by these monitors will
be in an inconsistent state, i.e. objects are
DS IN said to be damaged.
• suspend() (and the corresponding resume())
JAVA is deadlock-prone. If the suspended thread
holds a lock on the monitor protecting a
critical system resource, no thread can
access this resource until the target thread is
resumed. If the thread that would resume the
target thread attempts to lock this monitor
prior to calling resume(), deadlock results.
QUESTI Can we start a thread twice?

ON
class A extends Thread {
public void run() {
for (int i=1; i<=5; i++) {
EXAMP if (i==2) yield();

LE: System.out.println(“A: ” + i);

YIELD() }
System.out.println(“Exit from A”);
}
}
class B extends Thread {
public void run() {

EXAMP for (int j=1; j<=5; j++) {


System.out.println(“B: ” + j);
LE: }
YIELD() System.out.println(“Exit from B”);
}
}
class yieldTest {
public static void main(String[] args) {

EXAMP A a = new A();


B b = new B();
LE: a.start();
YIELD() b.start();
}
}
class C extends Thread {
public void run() {
for (int i=1; i<=5; i++) {
try {
if (i==2) sleep(2000);
} catch (Exception e) {}

EXAMP }
System.out.println(“C: ” + i);

LE:
System.out.println(“Exit from C”);
}
}
SLEEP() class yieldTest {
public static void main(String[] args) {
C c = new C();
c.start();
}
}
Every thread has a priority.
The OS refers to the priority level to
schedule the threads.

THREAD Priorities ranging between MIN_PRIORITY


and MAX_PRIORITY
PRIORIT Question:
Y  What is the default priority?

Higher priority implies more important


threads and allocated processor time before
lower priority threads.
 No guarantee though – platform dependent.
class priorityTest {
public static void main(String[] args) {
C c = new C();
A a = new A();
THREAD a.setPriority(10);

PRIORIT c.setPriority(1);

Y c.start();
a.start();
}
}
EXAMP isAlive() tests if a thread is alive.
LE:  A thread is alive if it has been started and has
not yet died.

ISALIVE Join() waits for a thread to die.


() AND  Causes current thread to stop executing until
the thread it joins with completes it tasks.

JOIN()  Question: why using join()?


class A extends Thread {
public void run() {
System.out.println(“Status: ” + isAlive());
}
EXAMP }

LE: class aliveTest() {


public static void main(String[] args) {

ISALIVE
A a = new A();
a.start();
try {
() AND }
a.join();

JOIN() }
catch (InterruptedException e) {}
System.out.println(“Status: ” + isAlive());

}
class MyClass2 implements Runnable{

@Override
public void run() {
Thread t = Thread.currentThread();

EXAMP System.out.println("Thread started:


"+t.getName());

LE: try {
Thread.sleep(4000);

JOIN() } catch (InterruptedException ie) {


ie.printStackTrace();
}
System.out.println("Thread ended:
"+t.getName());
}
}
public class JoinExample {
public static void main(String[] args) {
Thread th1 = new Thread(new MyClass(), "th1");
Thread th2 = new Thread(new MyClass(), "th2");
Thread th3 = new Thread(new MyClass(), "th3");
// Start first thread immediately
th1.start();

EXAMP
/* Start second thread(th2) once first thread(th1) is dead */
try { th1.join();

LE:
} catch (InterruptedException ie) { ie.printStackTrace(); }
th2.start();
/* Start third thread(th3) once second thread(th2) is dead */

JOIN() try { th2.join();


} catch (InterruptedException ie) { ie.printStackTrace(); }
th3.start();
// Displaying a message once third thread is dead
try { th3.join();
} catch (InterruptedException ie) { ie.printStackTrace(); }
System.out.println("All three threads have finished execution");
}
}

You might also like