SlideShare a Scribd company logo
1 of 74
Download to read offline
1
Java ThreadsJava Threads
2
Topics
โ— What is a thread?
โ— Thread states
โ— Thread priorities
โ— Thread class
โ— Two ways of creating Java threads
โ€“ Extending Thread class
โ€“ Implementing Runnable interface
โ— ThreadGroup
โ— Synchronization
โ— Inter-thread communication
โ— Scheduling a task via Timer and TimerTask
3
What is a Thread?What is a Thread?
4
Threads
โ— Why threads?
โ€“ Need to handle concurrent processes
โ— Definition
โ€“ Single sequential flow of control within a program
โ€“ For simplicity, think of threads as processes executed by
a program
โ€“ Example:
โ— Operating System
โ— HotJava web browser
5
Threads
6
Multi-threading in Java Platform
โ— Every application has at least one thread โ€” or
several, if you count "system" threads that do
things like memory management and signal
handling
โ— But from the application programmer's point of
view, you start with just one thread, called the main
thread. This thread has the ability to create
additional threads
7
Thread StatesThread States
8
Thread States
โ— A thread can in one of several possible states:
1.Running
โ— Currently running
โ— In control of CPU
2.Ready to run
โ— Can run but not yet given the chance
3.Resumed
โ— Ready to run after being suspended or block
4.Suspended
โ— Voluntarily allowed other threads to run
5.Blocked
โ— Waiting for some resource or event to occur
9
Thread PrioritiesThread Priorities
10
Thread Priorities
โ— Why priorities?
โ€“ Determine which thread receives CPU control and gets
to be executed first
โ— Definition:
โ€“ Integer value ranging from 1 to 10
โ€“ Higher the thread priority โ†’ larger chance of being
executed first
โ€“ Example:
โ— Two threads are ready to run
โ— First thread: priority of 5, already running
โ— Second thread = priority of 10, comes in while first thread
is running
11
Thread Priorities
โ— Context switch
โ€“ Occurs when a thread snatches the control of CPU from
another
โ€“ When does it occur?
โ— Running thread voluntarily relinquishes CPU control
โ— Running thread is preempted by a higher priority thread
โ— More than one highest priority thread that is ready
to run
โ€“ Deciding which receives CPU control depends on the
operating system
โ€“ Windows 95/98/NT: Uses time-sliced round-robin
โ€“ Solaris: Executing thread should voluntarily relinquish
CPU control
12
Thread ClassThread Class
13
The Thread Class: Constructor
โ— Has eight constructors
14
The Thread Class: Constants
โ— Contains fields for priority values
15
The Thread Class: Methods
โ— Some Thread methods
16
Two Ways of CreatingTwo Ways of Creating
Java ThreadsJava Threads
17
Two Ways of Creating and Starting
a Thread
1.Extending the Thread class
2.Implementing the Runnable interface
18
Extending ThreadExtending Thread
ClassClass
19
Extending Thread Class
โ— The subclass extends Thread class
โ€“ The subclass overrides the run() method of Thread class
โ— An object instance of the subclass can then be
created
โ— Calling the start() method of the object instance
starts the execution of the thread
โ€“ Java runtime starts the execution of the thread by
calling run() method of object instance
20
Two Schemes of starting a thread
from a subclass
1.The start() method is not in the constructor of the
subclass
โ€“ The start() method needs to be explicitly invoked after
object instance of the subclass is created in order to start
the thread
2.The start() method is in the constructor of the
subclass
โ€“ Creating an object instance of the subclass will start the
thread
21
Scheme 1: start() method is Not in
the constructor of subclass
1 class PrintNameThread extends Thread {
2 PrintNameThread(String name) {
3 super(name);
4 }
5 public void run() {
6 String name = getName();
7 for (int i = 0; i < 100; i++) {
8 System.out.print(name);
9 }
10 }
11 }
12 //continued
22
Scheme 1: start() method needs to
be called explicitly
14 class ExtendThreadClassTest1 {
15 public static void main(String args[]) {
16 PrintNameThread pnt1 =
17 new PrintNameThread("A");
18 pnt1.start(); // Start the first thread
19 PrintNameThread pnt2 =
20 new PrintNameThread("B");
21 pnt2.start(); // Start the second thread
22
23 }
24 }
23
Scheme 2: start() method is in a
constructor of the subclass
1 class PrintNameThread extends Thread {
2 PrintNameThread(String name) {
3 super(name);
4 start(); //runs the thread once instantiated
5 }
6 public void run() {
7 String name = getName();
8 for (int i = 0; i < 100; i++) {
9 System.out.print(name);
10 }
11 }
12 }
13 //continued
24
Scheme 2: Just creating an object
instance starts a thread
14 class ExtendThreadClassTest2 {
15 public static void main(String args[]) {
16 PrintNameThread pnt1 =
17 new PrintNameThread("A");
18 PrintNameThread pnt2 =
19 new PrintNameThread("B");
20
21 }
22 }
25
Scheme 2: Just creating an object
instance starts a thread
โ— Can modify main method as follows:
14 class ExtendThreadClassTest3 {
15 public static void main(String args[]) {
16 new PrintNameThread("A");
17 new PrintNameThread("B");
18 }
19 }
26
ImplementingImplementing
Runnable InterfaceRunnable Interface
27
Runnable Interface
โ— The Runnable interface should be implemented by
any class whose instances are intended to be
executed as a thread
โ— The class must define run() method of no
arguments
โ€“ The run() method is like main() for the new thread
โ— Provides the means for a class to be active while
not subclassing Thread
โ€“ A class that implements Runnable can run without
subclassing Thread by instantiating a Thread instance
and passing itself in as the target
28
Two Ways of Starting a Thread For
a class that implements Runnable
1.Caller thread creates Thread object and starts it
explicitly after an object instance of the class that
implements Runnable interface is created
โ€“ The start() method of the Thread object needs to be
explicitly invoked after object instance is created
2.The Thread object is created and started within the
constructor method of the class that implements
Runnable interface
โ€“ The caller thread just needs to create object instances of
the Runnable class
29
Scheme 1: Caller thread creates a
Thread object and starts it explicitly
// PrintNameRunnable implements Runnable interface
class PrintNameRunnable implements Runnable {
String name;
PrintNameRunnable(String name) {
this.name = name;
}
// Implementation of the run() defined in the
// Runnable interface.
public void run() {
for (int i = 0; i < 10; i++) {
System.out.print(name);
}
}
}
30
Scheme 1: Caller thread creates a
Thread object and starts it explicitly
public class RunnableThreadTest1 {
public static void main(String args[]) {
PrintNameRunnable pnt1 = new PrintNameRunnable("A");
Thread t1 = new Thread(pnt1);
t1.start();
}
}
31
Scheme 2: Thread object is created
and started within a constructor
// PrintNameRunnable implements Runnable interface
class PrintNameRunnable implements Runnable {
Thread thread;
PrintNameRunnable(String name) {
thread = new Thread(this, name);
thread.start();
}
// Implementation of the run() defined in the
// Runnable interface.
public void run() {
String name = thread.getName();
for (int i = 0; i < 10; i++) {
System.out.print(name);
}
}
}
32
Scheme 2: Thread object is created
and started within a constructor
public class RunnableThreadTest2 {
public static void main(String args[]) {
// Since the constructor of the PrintNameRunnable
// object creates a Thread object and starts it,
// there is no need to do it here.
new PrintNameRunnable("A");
new PrintNameRunnable("B");
new PrintNameRunnable("C");
}
}
33
Extending Thread ClassExtending Thread Class
vs. Implementingvs. Implementing
Runnable InterfaceRunnable Interface
34
Extending Thread vs. Implementing
Runnable Interface
โ— Choosing between these two is a matter of taste
โ— Implementing the Runnable interface
โ€“ May take more work since we still
โ— Declare a Thread object
โ— Call the Thread methods on this object
โ€“ Your class can still extend other class
โ— Extending the Thread class
โ€“ Easier to implement
โ€“ Your class can no longer extend any other class
35
ThreadGroupThreadGroup
36
ThreadGroup Class
โ— A thread group represents a set of threads
โ— In addition, a thread group can also include other
thread groups
โ€“ The thread groups form a tree in which every thread
group except the initial thread group has a parent
โ— A thread is allowed to access information about its
own thread group, but not to access information
about its thread group's parent thread group or any
other thread groups.
37
Example: ThreadGroup
1 // Start three threads
2 new SimpleThread("Jamaica").start();
3 new SimpleThread("Fiji").start();
4 new SimpleThread("Bora Bora").start();
5
6 ThreadGroup group
7 = Thread.currentThread().getThreadGroup();
8
9 Thread[] tarray = new Thread[10];
10 int actualSize = group.enumerate(tarray);
11 for (int i=0; i<actualSize;i++){
12 System.out.println("Thread " +
13 tarray[i].getName() + " in thread group "
14 + group.getName());
15 }
38
SynchronizationSynchronization
39
Race condition & How to Solve it
โ— Race conditions occur when multiple,
asynchronously executing threads access the same
object (called a shared resource) returning
unexpected (wrong) results
โ— Example:
โ€“ Threads often need to share a common resource ie a
file, with one thread reading from the file while another
thread writes to the file
โ— They can be avoided by synchronizing the threads
which access the shared resource
40
An Unsynchronized Example
1 class TwoStrings {
2 static void print(String str1, String str2) {
3 System.out.print(str1);
4 try {
5 Thread.sleep(500);
6 } catch (InterruptedException ie) {
7 }
8 System.out.println(str2);
9 }
10 }
11 //continued...
41
An Unsynchronized Example
12 class PrintStringsThread implements Runnable {
13 Thread thread;
14 String str1, str2;
15 PrintStringsThread(String str1, String str2) {
16 this.str1 = str1;
17 this.str2 = str2;
18 thread = new Thread(this);
19 thread.start();
20 }
21 public void run() {
22 TwoStrings.print(str1, str2);
23 }
24 }
25 //continued...
42
An Unsynchronized Example
26 class TestThread {
27 public static void main(String args[]) {
28 new PrintStringsThread("Hello ", "there.");
29 new PrintStringsThread("How are ", "you?");
30 new PrintStringsThread("Thank you ",
31 "very much!");
32 }
33 }
43
An Unsynchronized Example
โ— Sample output:
Hello How are Thank you there.
you?
very much!
44
Synchronization:
Locking an Object
โ— A thread is synchronized by becoming an owner of
the object's monitor
โ€“ Consider it as locking an object
โ— A thread becomes the owner of the object's monitor
in one of three ways
โ€“ Option 1: Use synchronized method
โ€“ Option 2: Use synchronized statement on a common
object
45
Option 1: Use synchronized method
1 class TwoStrings {
2 synchronized static void print(String str1,
3 String str2) {
4 System.out.print(str1);
5 try {
6 Thread.sleep(500);
7 } catch (InterruptedException ie) {
8 }
9 System.out.println(str2);
10 }
11 }
12 //continued...
46
Option 1: Use synchronized method
13 class PrintStringsThread implements Runnable {
14 Thread thread;
15 String str1, str2;
16 PrintStringsThread(String str1, String str2) {
17 this.str1 = str1;
18 this.str2 = str2;
19 thread = new Thread(this);
20 thread.start();
21 }
22 public void run() {
23 TwoStrings.print(str1, str2);
24 }
25 }
26 //continued...
47
Option 1: Use synchronized method
27 class TestThread {
28 public static void main(String args[]) {
29 new PrintStringsThread("Hello ", "there.");
30 new PrintStringsThread("How are ", "you?");
31 new PrintStringsThread("Thank you ",
32 "very much!");
33 }
34 }
48
Option 1: Executing Synchronized
Method
โ— Sample output:
Hello there.
How are you?
Thank you very much!
49
Option 2: Use synchronized
statement on a common object
1 class TwoStrings {
2 static void print(String str1, String str2) {
3 System.out.print(str1);
4 try {
5 Thread.sleep(500);
6 } catch (InterruptedException ie) {
7 }
8 System.out.println(str2);
9 }
10 }
11 //continued...
50
Option 2: Use synchronized
statement on a common object
12 class PrintStringsThread implements Runnable {
13 Thread thread;
14 String str1, str2;
15 TwoStrings ts;
16 PrintStringsThread(String str1, String str2,
17 TwoStrings ts) {
18 this.str1 = str1;
19 this.str2 = str2;
20 this.ts = ts;
21 thread = new Thread(this);
22 thread.start();
23 }
24 //continued...
51
Option 2: Use synchronized
statement on a common object
25 public void run() {
26 synchronized (ts) {
27 ts.print(str1, str2);
28 }
29 }
30 }
31 class TestThread {
32 public static void main(String args[]) {
33 TwoStrings ts = new TwoStrings();
34 new PrintStringsThread("Hello ", "there.", ts);
35 new PrintStringsThread("How are ", "you?", ts);
36 new PrintStringsThread("Thank you ",
37 "very much!", ts);
38 }}
52
Inter-threadInter-thread
SynchronizationSynchronization
53
Inter-thread Communication:
Methods from Object Class
54
wait() method of Object Class
โ— wait() method causes a thread to release the lock it
is holding on an object; allowing another thread to
run
โ— wait() method is defined in the Object class
โ— wait() can only be invoked from within synchronized
code
โ— it should always be wrapped in a try block as it
throws IOExceptions
โ— wait() can only invoked by the thread that own's the
lock on the object
55
wait() method of Object Class
โ— When wait() is called, the thread becomes disabled for
scheduling and lies dormant until one of four things
occur:
โ€“ another thread invokes the notify() method for this object
and the scheduler arbitrarily chooses to run the thread
โ€“ another thread invokes the notifyAll() method for this
object
โ€“ another thread interrupts this thread
โ€“ the specified wait() time elapses
โ— When one of the above occurs, the thread becomes re-
available to the Thread scheduler and competes for a
lock on the object
โ— Once it regains the lock on the object, everything
resumes as if no suspension had occurred
56
notify() method
โ— Wakes up a single thread that is waiting on this
object's monitor
โ€“ If any threads are waiting on this object, one of them is
chosen to be awakened
โ€“ The choice is arbitrary and occurs at the discretion of the
implementation
โ— Can only be used within synchronized code
โ— The awakened thread will not be able to proceed
until the current thread relinquishes the lock on this
object
57
Inter-threadInter-thread
Communication:Communication:
Producer-ConsumerProducer-Consumer
ExampleExample
58
Inter-thread Communication
59
Producer-Consumer
โ— Imagine a scenario in which there exists two
distinct threads both operating on a single shared
data area
โ— One thread, the Producer inserts information into
the data area whilst the other thread, the
Consumer, removes information from that same
area
โ— In order for the Producer to insert information into
the data area, there must be enough space
โ€“ The Producer's sole function is to insert data into the
data-area, it is not allowed to remove any data from the
area.
60
Producer-Consumer
โ— For the Consumer to be able to remove information
from the data area, there must be information there
in the first place
โ€“ The sole function of the Consumer is to remove data
from the data area
โ— The solution of the Producer-Consumer problem
lies with devising a suitable communication protocol
through which the two processes may exchange
information.
โ— The definition of such a protocol is the main factor
that makes the Producer-Consumer problem
interesting in terms of concurrent systems
61
Unsynchronized Producer-Consumer
Example: CubbyHole.java
1 public class CubbyHole {
2 private int contents;
3
4 public int get() {
5 return contents;
6 }
7
8 public synchronized void put(int value) {
9 contents = value;
10 }
11 }
62
Unsynchronized Producer-
Consumer Example: Producer.java
1 public class Producer extends Thread {
2 private CubbyHole cubbyhole;
3 private int number;
4
5 public Producer(CubbyHole c, int number) {
6 cubbyhole = c;
7 this.number = number;
8 }
9
10 public void run() {
11 for (int i = 0; i < 10; i++) {
12 cubbyhole.put(i);
13 System.out.println("Producer #" + this.number
14 + " put: " + i);
15 try {
16 sleep((int)(Math.random() * 100));
17 } catch (InterruptedException e) { }
18 }
19 }
20 }
63
Unsynchronized Producer-Consumer
Example: Consumer.java
1 public class Consumer extends Thread {
2 private CubbyHole cubbyhole;
3 private int number;
4
5 public Consumer(CubbyHole c, int number) {
6 cubbyhole = c;
7 this.number = number;
8 }
9
10 public void run() {
11 int value = 0;
12 for (int i = 0; i < 10; i++) {
13 value = cubbyhole.get();
14 System.out.println("Consumer #" + this.number
15 + " got: " + value);
16 }
17 }
18 }
19
64
Unsynchronized Producer-
Consumer Example: Main program
1 public class ProducerConsumerUnsynchronized {
2
3 public static void main(String[] args) {
4
5 CubbyHole c = new CubbyHole();
6
7 Producer p1 = new Producer(c, 1);
8 Consumer c1 = new Consumer(c, 1);
9
10 p1.start();
11 c1.start();
12 }
13 }
65
Result of Unsynchronized
Producer-Consumer
โ— Results are unpredictable
โ€“ A number may be read before a number has been
produced
โ€“ Multiple numbers may be produced with only one or two
being read
66
Result of Unsynchronized
Producer-Consumer
Consumer #1 got: 0
Producer #1 put: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Consumer #1 got: 0
Producer #1 put: 1
Producer #1 put: 2
Producer #1 put: 3
Producer #1 put: 4
Producer #1 put: 5
Producer #1 put: 6
Producer #1 put: 7
Producer #1 put: 8
Producer #1 put: 9
67
Synchronized Producer-Consumer
Example: CubbyHole.java
1 public class CubbyHole {
2 private int contents;
3 private boolean available = false;
4
5 public synchronized int get() {
6 while (available == false) {
7 try {
8 wait();
9 } catch (InterruptedException e) { }
10 }
11 available = false;
12 notifyAll();
13 return contents;
14 }
15 // continued
68
Synchronized Producer-Consumer
Example: CubbyHole.java
1
2 public synchronized void put(int value) {
3 while (available == true) {
4 try {
5 wait();
6 } catch (InterruptedException e) { }
7 }
8 contents = value;
9 available = true;
10 notifyAll();
11 }
12 }
69
Result of Synchronized Producer-
Consumer
Producer 1 put: 0
Consumer 1 got: 0
Producer 1 put: 1
Consumer 1 got: 1
Producer 1 put: 2
Consumer 1 got: 2
Producer 1 put: 3
Consumer 1 got: 3
Producer 1 put: 4
Consumer 1 got: 4
Producer 1 put: 5
Consumer 1 got: 5
Producer 1 put: 6
Consumer 1 got: 6
Producer 1 put: 7
Consumer 1 got: 7
Producer 1 put: 8
Consumer 1 got: 8
Producer 1 put: 9
Consumer 1 got: 9
70
Scheduling a taskScheduling a task
via Timer &via Timer &
TimerTask ClassesTimerTask Classes
71
Timer Class
โ— Provides a facility for threads to schedule tasks for
future execution in a background thread
โ— Tasks may be scheduled for one-time execution, or
for repeated execution at regular intervals.
โ— Corresponding to each Timer object is a single
background thread that is used to execute all of the
timer's tasks, sequentially
โ— Timer tasks should complete quickly
โ€“ If a timer task takes excessive time to complete, it "hogs"
the timer's task execution thread. This can, in turn, delay
the execution of subsequent tasks, which may "bunch
up" and execute in rapid succession when (and if) the
offending task finally completes.
72
TimerTask Class
โ— Abstract class with an abstract method called run()
โ— Concrete class must implement the run() abstract
method
73
Example: Timer Class
public class TimerReminder {
Timer timer;
public TimerReminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
System.out.format("About to schedule task.%n");
new TimerReminder(5);
System.out.format("Task scheduled.%n");
}
}
74
Thank You!Thank You!

More Related Content

What's hot

Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
ย 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
ย 
Java constructors
Java constructorsJava constructors
Java constructorsQUONTRASOLUTIONS
ย 
Threads in Java
Threads in JavaThreads in Java
Threads in JavaGaurav Aggarwal
ย 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdmHarshal Misalkar
ย 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
ย 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
ย 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaPavith Gunasekara
ย 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programmingRiccardo Cardin
ย 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java Janu Jahnavi
ย 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
ย 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
ย 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
ย 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handlingNahian Ahmed
ย 

What's hot (20)

Exception handling
Exception handlingException handling
Exception handling
ย 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
ย 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
ย 
Java constructors
Java constructorsJava constructors
Java constructors
ย 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
ย 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
ย 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
ย 
Java threads
Java threadsJava threads
Java threads
ย 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
ย 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
ย 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
ย 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
ย 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
ย 
Method overloading
Method overloadingMethod overloading
Method overloading
ย 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
ย 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
ย 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
ย 
Java Streams
Java StreamsJava Streams
Java Streams
ย 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ย 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
ย 

Similar to java-thread

javathreads
javathreadsjavathreads
javathreadsArjun Shanka
ย 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
ย 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
ย 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
ย 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
ย 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
ย 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
ย 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
ย 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptxcreativegamerz00
ย 
Multithreading
MultithreadingMultithreading
MultithreadingSanthiNivas
ย 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
ย 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreadingRakesh Madugula
ย 
advanced java ppt
advanced java pptadvanced java ppt
advanced java pptPreetiDixit22
ย 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12Mahmoud Ouf
ย 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamNavaneethan Naveen
ย 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
ย 

Similar to java-thread (20)

javathreads
javathreadsjavathreads
javathreads
ย 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
ย 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
ย 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
ย 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
ย 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
ย 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
ย 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
ย 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
ย 
Multithreading
MultithreadingMultithreading
Multithreading
ย 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
ย 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
ย 
Threads
ThreadsThreads
Threads
ย 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
ย 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
ย 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
ย 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugam
ย 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
ย 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
ย 
Threads
ThreadsThreads
Threads
ย 

Recently uploaded

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
ย 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
ย 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
ย 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxnull - The Open Security Community
ย 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
ย 
Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”
Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”
Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”soniya singh
ย 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
ย 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
ย 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
ย 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
ย 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
ย 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
ย 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
ย 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
ย 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
ย 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
ย 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
ย 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
ย 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
ย 

Recently uploaded (20)

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
ย 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
ย 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
ย 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
ย 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
ย 
Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”
Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”
Model Call Girl in Narela Delhi reach out to us at ๐Ÿ”8264348440๐Ÿ”
ย 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ย 
โ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
โ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCRโ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
โ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
ย 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
ย 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
ย 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
ย 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
ย 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
ย 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
ย 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
ย 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
ย 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
ย 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
ย 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
ย 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
ย 

java-thread

  • 2. 2 Topics โ— What is a thread? โ— Thread states โ— Thread priorities โ— Thread class โ— Two ways of creating Java threads โ€“ Extending Thread class โ€“ Implementing Runnable interface โ— ThreadGroup โ— Synchronization โ— Inter-thread communication โ— Scheduling a task via Timer and TimerTask
  • 3. 3 What is a Thread?What is a Thread?
  • 4. 4 Threads โ— Why threads? โ€“ Need to handle concurrent processes โ— Definition โ€“ Single sequential flow of control within a program โ€“ For simplicity, think of threads as processes executed by a program โ€“ Example: โ— Operating System โ— HotJava web browser
  • 6. 6 Multi-threading in Java Platform โ— Every application has at least one thread โ€” or several, if you count "system" threads that do things like memory management and signal handling โ— But from the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads
  • 8. 8 Thread States โ— A thread can in one of several possible states: 1.Running โ— Currently running โ— In control of CPU 2.Ready to run โ— Can run but not yet given the chance 3.Resumed โ— Ready to run after being suspended or block 4.Suspended โ— Voluntarily allowed other threads to run 5.Blocked โ— Waiting for some resource or event to occur
  • 10. 10 Thread Priorities โ— Why priorities? โ€“ Determine which thread receives CPU control and gets to be executed first โ— Definition: โ€“ Integer value ranging from 1 to 10 โ€“ Higher the thread priority โ†’ larger chance of being executed first โ€“ Example: โ— Two threads are ready to run โ— First thread: priority of 5, already running โ— Second thread = priority of 10, comes in while first thread is running
  • 11. 11 Thread Priorities โ— Context switch โ€“ Occurs when a thread snatches the control of CPU from another โ€“ When does it occur? โ— Running thread voluntarily relinquishes CPU control โ— Running thread is preempted by a higher priority thread โ— More than one highest priority thread that is ready to run โ€“ Deciding which receives CPU control depends on the operating system โ€“ Windows 95/98/NT: Uses time-sliced round-robin โ€“ Solaris: Executing thread should voluntarily relinquish CPU control
  • 13. 13 The Thread Class: Constructor โ— Has eight constructors
  • 14. 14 The Thread Class: Constants โ— Contains fields for priority values
  • 15. 15 The Thread Class: Methods โ— Some Thread methods
  • 16. 16 Two Ways of CreatingTwo Ways of Creating Java ThreadsJava Threads
  • 17. 17 Two Ways of Creating and Starting a Thread 1.Extending the Thread class 2.Implementing the Runnable interface
  • 19. 19 Extending Thread Class โ— The subclass extends Thread class โ€“ The subclass overrides the run() method of Thread class โ— An object instance of the subclass can then be created โ— Calling the start() method of the object instance starts the execution of the thread โ€“ Java runtime starts the execution of the thread by calling run() method of object instance
  • 20. 20 Two Schemes of starting a thread from a subclass 1.The start() method is not in the constructor of the subclass โ€“ The start() method needs to be explicitly invoked after object instance of the subclass is created in order to start the thread 2.The start() method is in the constructor of the subclass โ€“ Creating an object instance of the subclass will start the thread
  • 21. 21 Scheme 1: start() method is Not in the constructor of subclass 1 class PrintNameThread extends Thread { 2 PrintNameThread(String name) { 3 super(name); 4 } 5 public void run() { 6 String name = getName(); 7 for (int i = 0; i < 100; i++) { 8 System.out.print(name); 9 } 10 } 11 } 12 //continued
  • 22. 22 Scheme 1: start() method needs to be called explicitly 14 class ExtendThreadClassTest1 { 15 public static void main(String args[]) { 16 PrintNameThread pnt1 = 17 new PrintNameThread("A"); 18 pnt1.start(); // Start the first thread 19 PrintNameThread pnt2 = 20 new PrintNameThread("B"); 21 pnt2.start(); // Start the second thread 22 23 } 24 }
  • 23. 23 Scheme 2: start() method is in a constructor of the subclass 1 class PrintNameThread extends Thread { 2 PrintNameThread(String name) { 3 super(name); 4 start(); //runs the thread once instantiated 5 } 6 public void run() { 7 String name = getName(); 8 for (int i = 0; i < 100; i++) { 9 System.out.print(name); 10 } 11 } 12 } 13 //continued
  • 24. 24 Scheme 2: Just creating an object instance starts a thread 14 class ExtendThreadClassTest2 { 15 public static void main(String args[]) { 16 PrintNameThread pnt1 = 17 new PrintNameThread("A"); 18 PrintNameThread pnt2 = 19 new PrintNameThread("B"); 20 21 } 22 }
  • 25. 25 Scheme 2: Just creating an object instance starts a thread โ— Can modify main method as follows: 14 class ExtendThreadClassTest3 { 15 public static void main(String args[]) { 16 new PrintNameThread("A"); 17 new PrintNameThread("B"); 18 } 19 }
  • 27. 27 Runnable Interface โ— The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread โ— The class must define run() method of no arguments โ€“ The run() method is like main() for the new thread โ— Provides the means for a class to be active while not subclassing Thread โ€“ A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target
  • 28. 28 Two Ways of Starting a Thread For a class that implements Runnable 1.Caller thread creates Thread object and starts it explicitly after an object instance of the class that implements Runnable interface is created โ€“ The start() method of the Thread object needs to be explicitly invoked after object instance is created 2.The Thread object is created and started within the constructor method of the class that implements Runnable interface โ€“ The caller thread just needs to create object instances of the Runnable class
  • 29. 29 Scheme 1: Caller thread creates a Thread object and starts it explicitly // PrintNameRunnable implements Runnable interface class PrintNameRunnable implements Runnable { String name; PrintNameRunnable(String name) { this.name = name; } // Implementation of the run() defined in the // Runnable interface. public void run() { for (int i = 0; i < 10; i++) { System.out.print(name); } } }
  • 30. 30 Scheme 1: Caller thread creates a Thread object and starts it explicitly public class RunnableThreadTest1 { public static void main(String args[]) { PrintNameRunnable pnt1 = new PrintNameRunnable("A"); Thread t1 = new Thread(pnt1); t1.start(); } }
  • 31. 31 Scheme 2: Thread object is created and started within a constructor // PrintNameRunnable implements Runnable interface class PrintNameRunnable implements Runnable { Thread thread; PrintNameRunnable(String name) { thread = new Thread(this, name); thread.start(); } // Implementation of the run() defined in the // Runnable interface. public void run() { String name = thread.getName(); for (int i = 0; i < 10; i++) { System.out.print(name); } } }
  • 32. 32 Scheme 2: Thread object is created and started within a constructor public class RunnableThreadTest2 { public static void main(String args[]) { // Since the constructor of the PrintNameRunnable // object creates a Thread object and starts it, // there is no need to do it here. new PrintNameRunnable("A"); new PrintNameRunnable("B"); new PrintNameRunnable("C"); } }
  • 33. 33 Extending Thread ClassExtending Thread Class vs. Implementingvs. Implementing Runnable InterfaceRunnable Interface
  • 34. 34 Extending Thread vs. Implementing Runnable Interface โ— Choosing between these two is a matter of taste โ— Implementing the Runnable interface โ€“ May take more work since we still โ— Declare a Thread object โ— Call the Thread methods on this object โ€“ Your class can still extend other class โ— Extending the Thread class โ€“ Easier to implement โ€“ Your class can no longer extend any other class
  • 36. 36 ThreadGroup Class โ— A thread group represents a set of threads โ— In addition, a thread group can also include other thread groups โ€“ The thread groups form a tree in which every thread group except the initial thread group has a parent โ— A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups.
  • 37. 37 Example: ThreadGroup 1 // Start three threads 2 new SimpleThread("Jamaica").start(); 3 new SimpleThread("Fiji").start(); 4 new SimpleThread("Bora Bora").start(); 5 6 ThreadGroup group 7 = Thread.currentThread().getThreadGroup(); 8 9 Thread[] tarray = new Thread[10]; 10 int actualSize = group.enumerate(tarray); 11 for (int i=0; i<actualSize;i++){ 12 System.out.println("Thread " + 13 tarray[i].getName() + " in thread group " 14 + group.getName()); 15 }
  • 39. 39 Race condition & How to Solve it โ— Race conditions occur when multiple, asynchronously executing threads access the same object (called a shared resource) returning unexpected (wrong) results โ— Example: โ€“ Threads often need to share a common resource ie a file, with one thread reading from the file while another thread writes to the file โ— They can be avoided by synchronizing the threads which access the shared resource
  • 40. 40 An Unsynchronized Example 1 class TwoStrings { 2 static void print(String str1, String str2) { 3 System.out.print(str1); 4 try { 5 Thread.sleep(500); 6 } catch (InterruptedException ie) { 7 } 8 System.out.println(str2); 9 } 10 } 11 //continued...
  • 41. 41 An Unsynchronized Example 12 class PrintStringsThread implements Runnable { 13 Thread thread; 14 String str1, str2; 15 PrintStringsThread(String str1, String str2) { 16 this.str1 = str1; 17 this.str2 = str2; 18 thread = new Thread(this); 19 thread.start(); 20 } 21 public void run() { 22 TwoStrings.print(str1, str2); 23 } 24 } 25 //continued...
  • 42. 42 An Unsynchronized Example 26 class TestThread { 27 public static void main(String args[]) { 28 new PrintStringsThread("Hello ", "there."); 29 new PrintStringsThread("How are ", "you?"); 30 new PrintStringsThread("Thank you ", 31 "very much!"); 32 } 33 }
  • 43. 43 An Unsynchronized Example โ— Sample output: Hello How are Thank you there. you? very much!
  • 44. 44 Synchronization: Locking an Object โ— A thread is synchronized by becoming an owner of the object's monitor โ€“ Consider it as locking an object โ— A thread becomes the owner of the object's monitor in one of three ways โ€“ Option 1: Use synchronized method โ€“ Option 2: Use synchronized statement on a common object
  • 45. 45 Option 1: Use synchronized method 1 class TwoStrings { 2 synchronized static void print(String str1, 3 String str2) { 4 System.out.print(str1); 5 try { 6 Thread.sleep(500); 7 } catch (InterruptedException ie) { 8 } 9 System.out.println(str2); 10 } 11 } 12 //continued...
  • 46. 46 Option 1: Use synchronized method 13 class PrintStringsThread implements Runnable { 14 Thread thread; 15 String str1, str2; 16 PrintStringsThread(String str1, String str2) { 17 this.str1 = str1; 18 this.str2 = str2; 19 thread = new Thread(this); 20 thread.start(); 21 } 22 public void run() { 23 TwoStrings.print(str1, str2); 24 } 25 } 26 //continued...
  • 47. 47 Option 1: Use synchronized method 27 class TestThread { 28 public static void main(String args[]) { 29 new PrintStringsThread("Hello ", "there."); 30 new PrintStringsThread("How are ", "you?"); 31 new PrintStringsThread("Thank you ", 32 "very much!"); 33 } 34 }
  • 48. 48 Option 1: Executing Synchronized Method โ— Sample output: Hello there. How are you? Thank you very much!
  • 49. 49 Option 2: Use synchronized statement on a common object 1 class TwoStrings { 2 static void print(String str1, String str2) { 3 System.out.print(str1); 4 try { 5 Thread.sleep(500); 6 } catch (InterruptedException ie) { 7 } 8 System.out.println(str2); 9 } 10 } 11 //continued...
  • 50. 50 Option 2: Use synchronized statement on a common object 12 class PrintStringsThread implements Runnable { 13 Thread thread; 14 String str1, str2; 15 TwoStrings ts; 16 PrintStringsThread(String str1, String str2, 17 TwoStrings ts) { 18 this.str1 = str1; 19 this.str2 = str2; 20 this.ts = ts; 21 thread = new Thread(this); 22 thread.start(); 23 } 24 //continued...
  • 51. 51 Option 2: Use synchronized statement on a common object 25 public void run() { 26 synchronized (ts) { 27 ts.print(str1, str2); 28 } 29 } 30 } 31 class TestThread { 32 public static void main(String args[]) { 33 TwoStrings ts = new TwoStrings(); 34 new PrintStringsThread("Hello ", "there.", ts); 35 new PrintStringsThread("How are ", "you?", ts); 36 new PrintStringsThread("Thank you ", 37 "very much!", ts); 38 }}
  • 54. 54 wait() method of Object Class โ— wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run โ— wait() method is defined in the Object class โ— wait() can only be invoked from within synchronized code โ— it should always be wrapped in a try block as it throws IOExceptions โ— wait() can only invoked by the thread that own's the lock on the object
  • 55. 55 wait() method of Object Class โ— When wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur: โ€“ another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread โ€“ another thread invokes the notifyAll() method for this object โ€“ another thread interrupts this thread โ€“ the specified wait() time elapses โ— When one of the above occurs, the thread becomes re- available to the Thread scheduler and competes for a lock on the object โ— Once it regains the lock on the object, everything resumes as if no suspension had occurred
  • 56. 56 notify() method โ— Wakes up a single thread that is waiting on this object's monitor โ€“ If any threads are waiting on this object, one of them is chosen to be awakened โ€“ The choice is arbitrary and occurs at the discretion of the implementation โ— Can only be used within synchronized code โ— The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object
  • 59. 59 Producer-Consumer โ— Imagine a scenario in which there exists two distinct threads both operating on a single shared data area โ— One thread, the Producer inserts information into the data area whilst the other thread, the Consumer, removes information from that same area โ— In order for the Producer to insert information into the data area, there must be enough space โ€“ The Producer's sole function is to insert data into the data-area, it is not allowed to remove any data from the area.
  • 60. 60 Producer-Consumer โ— For the Consumer to be able to remove information from the data area, there must be information there in the first place โ€“ The sole function of the Consumer is to remove data from the data area โ— The solution of the Producer-Consumer problem lies with devising a suitable communication protocol through which the two processes may exchange information. โ— The definition of such a protocol is the main factor that makes the Producer-Consumer problem interesting in terms of concurrent systems
  • 61. 61 Unsynchronized Producer-Consumer Example: CubbyHole.java 1 public class CubbyHole { 2 private int contents; 3 4 public int get() { 5 return contents; 6 } 7 8 public synchronized void put(int value) { 9 contents = value; 10 } 11 }
  • 62. 62 Unsynchronized Producer- Consumer Example: Producer.java 1 public class Producer extends Thread { 2 private CubbyHole cubbyhole; 3 private int number; 4 5 public Producer(CubbyHole c, int number) { 6 cubbyhole = c; 7 this.number = number; 8 } 9 10 public void run() { 11 for (int i = 0; i < 10; i++) { 12 cubbyhole.put(i); 13 System.out.println("Producer #" + this.number 14 + " put: " + i); 15 try { 16 sleep((int)(Math.random() * 100)); 17 } catch (InterruptedException e) { } 18 } 19 } 20 }
  • 63. 63 Unsynchronized Producer-Consumer Example: Consumer.java 1 public class Consumer extends Thread { 2 private CubbyHole cubbyhole; 3 private int number; 4 5 public Consumer(CubbyHole c, int number) { 6 cubbyhole = c; 7 this.number = number; 8 } 9 10 public void run() { 11 int value = 0; 12 for (int i = 0; i < 10; i++) { 13 value = cubbyhole.get(); 14 System.out.println("Consumer #" + this.number 15 + " got: " + value); 16 } 17 } 18 } 19
  • 64. 64 Unsynchronized Producer- Consumer Example: Main program 1 public class ProducerConsumerUnsynchronized { 2 3 public static void main(String[] args) { 4 5 CubbyHole c = new CubbyHole(); 6 7 Producer p1 = new Producer(c, 1); 8 Consumer c1 = new Consumer(c, 1); 9 10 p1.start(); 11 c1.start(); 12 } 13 }
  • 65. 65 Result of Unsynchronized Producer-Consumer โ— Results are unpredictable โ€“ A number may be read before a number has been produced โ€“ Multiple numbers may be produced with only one or two being read
  • 66. 66 Result of Unsynchronized Producer-Consumer Consumer #1 got: 0 Producer #1 put: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Producer #1 put: 1 Producer #1 put: 2 Producer #1 put: 3 Producer #1 put: 4 Producer #1 put: 5 Producer #1 put: 6 Producer #1 put: 7 Producer #1 put: 8 Producer #1 put: 9
  • 67. 67 Synchronized Producer-Consumer Example: CubbyHole.java 1 public class CubbyHole { 2 private int contents; 3 private boolean available = false; 4 5 public synchronized int get() { 6 while (available == false) { 7 try { 8 wait(); 9 } catch (InterruptedException e) { } 10 } 11 available = false; 12 notifyAll(); 13 return contents; 14 } 15 // continued
  • 68. 68 Synchronized Producer-Consumer Example: CubbyHole.java 1 2 public synchronized void put(int value) { 3 while (available == true) { 4 try { 5 wait(); 6 } catch (InterruptedException e) { } 7 } 8 contents = value; 9 available = true; 10 notifyAll(); 11 } 12 }
  • 69. 69 Result of Synchronized Producer- Consumer Producer 1 put: 0 Consumer 1 got: 0 Producer 1 put: 1 Consumer 1 got: 1 Producer 1 put: 2 Consumer 1 got: 2 Producer 1 put: 3 Consumer 1 got: 3 Producer 1 put: 4 Consumer 1 got: 4 Producer 1 put: 5 Consumer 1 got: 5 Producer 1 put: 6 Consumer 1 got: 6 Producer 1 put: 7 Consumer 1 got: 7 Producer 1 put: 8 Consumer 1 got: 8 Producer 1 put: 9 Consumer 1 got: 9
  • 70. 70 Scheduling a taskScheduling a task via Timer &via Timer & TimerTask ClassesTimerTask Classes
  • 71. 71 Timer Class โ— Provides a facility for threads to schedule tasks for future execution in a background thread โ— Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. โ— Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially โ— Timer tasks should complete quickly โ€“ If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.
  • 72. 72 TimerTask Class โ— Abstract class with an abstract method called run() โ— Concrete class must implement the run() abstract method
  • 73. 73 Example: Timer Class public class TimerReminder { Timer timer; public TimerReminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.format("Time's up!%n"); timer.cancel(); //Terminate the timer thread } } public static void main(String args[]) { System.out.format("About to schedule task.%n"); new TimerReminder(5); System.out.format("Task scheduled.%n"); } }