SlideShare a Scribd company logo
1 of 22
Threads

Ben Abdallah Helmi Architect J2EE
Note that calling your thread’s start() method doesn’t immediately cause
the thread to run; it just makes the thread Eligible to run

1. public class CounterThread
extends Thread {
2. public void run() {
3. for (int i = 1; i <= 10; i++) {
4.
System.out.println(“Countin
g: “ + i);
5. }
6. }
7. }
1. CounterThread ct = new
CounterThread();
2. ct.start(); // start(), not run()

1. public class DownCounter
implements Runnable {
2. public void run() {
3. for (int i = 10; i >= 1; i——)
{
4.
System.out.println(“Countin
g Down: “ + i);
5. }
6. }
7. }
1. DownCounter dc = new
DownCounter();
2. Thread t = new Thread(dc);
3. t.start();

Ben Abdallah Helmi Architect J2EE
When Execution Ends
When the run() method returns, the
thread has finished its task and is
considered dead.
 You can’t restart a dead thread by
calling its start() or run() methods.
 You can call other methods (besides
start() and run()) of a dead thread.


Ben Abdallah Helmi Architect J2EE
Thread States

Ben Abdallah Helmi Architect J2EE
Thread Priorities
Every thread has a priority, which is an integer from 1 to
10; threads with higher priority should get preference
over threads with lower priority. The thread scheduler
considers the priority when it decides which ready
thread should execute. The scheduler generally
chooses the highest-priority waiting thread. If more than
one thread is waiting, the scheduler chooses one of
them. There is no guarantee that the thread chosen will
be the one that has been waiting the longest.
The default priority is 5, but all newly created threads have
their priority set to that of the creating thread. To set a
thread’s priority, call the setPriority() method, passing in
the desired new priority. The getPriority() method
returns a thread’s priority.
Insteadof hard-coding the value 10, the fragment uses the
constant MAX_PRIORITY. The Thread class also
defines constants for MIN_PRIORITY (which is 1) and
NORM_PRIORITY (which is 5). Ben Abdallah Helmi Architect J2EE
Daemon Threads
Daemon threads are infrastructure threads, created
automatically by the JVM. The garbage collector is a
daemon thread, and so is the GUI event-processing
thread.
When an application begins to run, there is only one nondaemon thread in existence: the main thread, which
runs your main() method. Any threads created by
daemon threads are initially daemon threads. Threads
created by non-daemon threads are initially nondaemon threads. Before a thread begins execution, you
can change its daemon status by calling its
setDaemon() method, which takes a boolean argument.
The JVM runs until the only live threads are daemons.
In other words, the JVM considers its work to be done
when the only remaining threads are its own
infrastructure threads
Ben Abdallah Helmi Architect J2EE
Controlling Threads
Yielding
 Suspending and then resuming
 Sleeping and then waking up
 Blocking and then continuing
 Waiting and then being notified


Ben Abdallah Helmi Architect J2EE
Yielding
A thread can offer to move out of the
virtual CPU by yielding.
 The yield() method is a static method of
the Thread class. It always causes the
currently executing thread to yield.
 Yielding allows a time-consuming thread
to permit other threads to execute.


Ben Abdallah Helmi Architect J2EE
Suspending


The exact effect of suspend() and
resume() is much better implemented
using wait() and notify().

Ben Abdallah Helmi Architect J2EE
Sleeping
A sleeping thread passes time without doing
anything and without using the CPU.
 public static void sleep(long milliseconds) throws
InterruptedException Or public static void
sleep(long milliseconds, int nanoseconds) throws
InterruptedException
 The Thread class has a method called interrupt().
A sleeping thread that receives an interrupt() call
moves immediately into the Ready state; when it
gets to run, it will execute its InterruptedException
handler


Ben Abdallah Helmi Architect J2EE
Blocking
Many methods that perform input or output have to wait
for some occurrence in the outside world before they
can proceed; this behavior is known as blocking. A good
example is reading from a socket:
1. try {
2. Socket sock = new Socket(“magnesium”, 5505);
3. InputStream istr = sock.getInputStream();
4. int b = istr.read();
5. }
6. catch (IOException ex) {
7. // Handle the exception
8. }

Ben Abdallah Helmi Architect J2EE
Monitor States
The wait() method puts an executing
thread into the Waiting state, and the
notify() and notifyAll() methods move
waiting threads out of the Waiting
state. However, these methods are
very different from
suspend(), resume(), and yield(). For
one thing, they are implemented in the
Object class, not in Thread. For
another, they can be called only in
synchronized code
Ben Abdallah Helmi Architect J2EE
Java’s monitor support addresses
these issues by providing the following
resources:
 A lock for each object
 The synchronized keyword for
accessing an object’s lock
 The wait(), notify(), and notifyAll()
methods, which allow the object to
control client threads


Ben Abdallah Helmi Architect J2EE
The Object Lock and
Synchronization


Every object has a lock. At any moment, that lock is
controlled by, at most, one single thread. The lock controls
access to the object’s synchronized code. A thread that wants
to execute an object’s synchronized code must first attempt to
acquire that object’s lock. If the lock is available— that is, if it
is not already controlled by another thread—then all is well. If
the lock is under another thread’s control, then the attempting
thread goes into the Seeking Lock state and becomes ready
only when the lock becomes available. When a thread that
owns a lock passes out of the synchronized code, the thread
automatically gives up the lock. All this lockchecking and
state-changing is done behind the scenes; the only explicit
programming you need to do is to declare code to be
synchronized.

Ben Abdallah Helmi Architect J2EE
wait() and notify()


The wait() and notify() methods
provide a way for a shared object to
pause a thread when it becomes
unavailable to that thread and to allow
the thread to continue when
appropriate. The threads themselves
never have to check the state of the
shared object.

Ben Abdallah Helmi Architect J2EE


Both wait() and notify() must be called
in synchronized code. A thread that
calls wait() releases the virtual CPU;
at the same time, it releases the lock.
It enters a pool of waiting
threads, which is managed by the
object whose wait() method got called.
Every object has such a pool.

Ben Abdallah Helmi Architect J2EE
1. public synchronized
String retrieveMessage()
{
2. while (request == false) {
3. try {
4. wait();
5. } catch
(InterruptedException e) {
}
6. }
7. request = false;
8. return message;
9. }

1. public synchronized void
2. storeMessage(String
message) {
3. this.message = message;
4. request = true;
5. notify();
6. }
The notify() method
rbitrarily selects one of
the threads in the
monitor’s waiting pool
and moves it to the
Seeking Lock state.
Eventually that thread
will acquire the mailbox’s
lock and can proceed
with execution.
Ben Abdallah Helmi Architect J2EE










Here are the main points to remember about
wait():
The calling thread gives up the CPU.
The calling thread gives up the lock.
The calling thread goes into the monitor’s
waiting pool.
Here are the main points to remember about
notify():
One arbitrarily chosen thread gets moved
out of the monitor’s waiting pool and into the
Seeking Lock state.
The thread that was notified must reacquire
the monitor’s lock before it can proceed.
Ben Abdallah Helmi Architect J2EE
The Class Lock
It is clear by now that every object (that
is, every instance of every class) has a lock.
Every class
also has a lock. The class lock controls access
to all synchronized static code in the class.
Consider
the following example:
class X {
static int x, y;
static synchronized void foo() {
x++;
y++;
}
Ben Abdallah Helmi Architect J2EE
}
notifyAll(): Always check the monitor’s state in a while loop rather than
an if statement.
After changing the monitor’s state, call notifyAll() rather than notify().

1. public synchronized
void mixedUpMethod()
{
2. if (i<16 || f>4.3f ||
message.equals(“UHOH”) {
3. try { wait(); } catch
(InterruptedException
e) { }
4. }
5.
6. // Proceed in a way
that changes
state, and then...
7. notify();
8. }

1. public synchronized
void mixedUpMethod()
{
2. while (i<16 || f>4.3f ||
message.equals(“UHOH”) {
3. try { wait(); } catch
(InterruptedException
e) { }
4. }
5.
6. // Proceed in a way
that changes
state, and then...
7. notifyAll();
8. }
Ben Abdallah Helmi Architect J2EE
Synchronizing Part of a
Method
1. class StrangeSync {
2. Rectangle rect = new
Rectangle(11, 13, 1100, 1300
);
3. void doit() {
4. int x = 504;
5. int y = x / 3;
6. rect.width -= x;
7. rect.height -= y;
8. }
9. }
perhaps you want to
synchronize only lines 6
and 7, and perhaps you
want a thread attempting to
execute those lines to
synchronize on the lock of
rect, rather than on the lock
of the current executing
object. The way to do this is
shown here:

1. class StrangeSync {
2. Rectangle rect = new
Rectangle(11, 13, 1100, 1300
);
3. void doit() {
4. int x = 504;
5. int y = x / 3;
6. synchronized(rect) {
7. rect.width -= x;
8. rect.height -= y;
9. }
10. }
11. }

Ben Abdallah Helmi Architect J2EE






To synchronize an entire method, using
the lock of the object that owns the
method. To do this, put the synchronized
keyword in the method’s declaration.
To synchronize part of a method, using
the lock of an arbitrary object. Put curly
brackets around the code to be
synchronized, preceded by
synchronized(theArbitraryObject).
To synchronize part of a method, using
the lock of the object that owns the
method. Put curly brackets around the
code to be synchronized, preceded by
synchronized(this).
Ben Abdallah Helmi Architect J2EE

More Related Content

What's hot

[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Ciklum Minsk
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 

What's hot (20)

[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Threads
ThreadsThreads
Threads
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
04 threads
04 threads04 threads
04 threads
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 

Similar to chap 7 : Threads (scjp/ocjp)

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .happycocoman
 
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
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.pptssuserec53e73
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 

Similar to chap 7 : Threads (scjp/ocjp) (20)

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).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
 
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
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Threads
ThreadsThreads
Threads
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 

More from It Academy

Chapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesChapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesIt Academy
 
Chapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration TechnologiesChapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration TechnologiesIt Academy
 
Chapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesChapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesIt Academy
 
Chapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UMLChapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UMLIt Academy
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismIt Academy
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceIt Academy
 
Chapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their RelationshipsChapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their RelationshipsIt Academy
 
Chapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionChapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionIt Academy
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsIt Academy
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and StringsIt Academy
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsIt Academy
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)It Academy
 
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)It Academy
 
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)It Academy
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)It Academy
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)It Academy
 
chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)It Academy
 

More from It Academy (20)

Chapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesChapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side Technologies
 
Chapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration TechnologiesChapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration Technologies
 
Chapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesChapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side Technologies
 
Chapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UMLChapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UML
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class Inheritance
 
Chapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their RelationshipsChapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their Relationships
 
Chapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionChapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class Construction
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic Concepts
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
 
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)
 
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
 
chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

chap 7 : Threads (scjp/ocjp)

  • 1. Threads Ben Abdallah Helmi Architect J2EE
  • 2. Note that calling your thread’s start() method doesn’t immediately cause the thread to run; it just makes the thread Eligible to run 1. public class CounterThread extends Thread { 2. public void run() { 3. for (int i = 1; i <= 10; i++) { 4. System.out.println(“Countin g: “ + i); 5. } 6. } 7. } 1. CounterThread ct = new CounterThread(); 2. ct.start(); // start(), not run() 1. public class DownCounter implements Runnable { 2. public void run() { 3. for (int i = 10; i >= 1; i——) { 4. System.out.println(“Countin g Down: “ + i); 5. } 6. } 7. } 1. DownCounter dc = new DownCounter(); 2. Thread t = new Thread(dc); 3. t.start(); Ben Abdallah Helmi Architect J2EE
  • 3. When Execution Ends When the run() method returns, the thread has finished its task and is considered dead.  You can’t restart a dead thread by calling its start() or run() methods.  You can call other methods (besides start() and run()) of a dead thread.  Ben Abdallah Helmi Architect J2EE
  • 4. Thread States Ben Abdallah Helmi Architect J2EE
  • 5. Thread Priorities Every thread has a priority, which is an integer from 1 to 10; threads with higher priority should get preference over threads with lower priority. The thread scheduler considers the priority when it decides which ready thread should execute. The scheduler generally chooses the highest-priority waiting thread. If more than one thread is waiting, the scheduler chooses one of them. There is no guarantee that the thread chosen will be the one that has been waiting the longest. The default priority is 5, but all newly created threads have their priority set to that of the creating thread. To set a thread’s priority, call the setPriority() method, passing in the desired new priority. The getPriority() method returns a thread’s priority. Insteadof hard-coding the value 10, the fragment uses the constant MAX_PRIORITY. The Thread class also defines constants for MIN_PRIORITY (which is 1) and NORM_PRIORITY (which is 5). Ben Abdallah Helmi Architect J2EE
  • 6. Daemon Threads Daemon threads are infrastructure threads, created automatically by the JVM. The garbage collector is a daemon thread, and so is the GUI event-processing thread. When an application begins to run, there is only one nondaemon thread in existence: the main thread, which runs your main() method. Any threads created by daemon threads are initially daemon threads. Threads created by non-daemon threads are initially nondaemon threads. Before a thread begins execution, you can change its daemon status by calling its setDaemon() method, which takes a boolean argument. The JVM runs until the only live threads are daemons. In other words, the JVM considers its work to be done when the only remaining threads are its own infrastructure threads Ben Abdallah Helmi Architect J2EE
  • 7. Controlling Threads Yielding  Suspending and then resuming  Sleeping and then waking up  Blocking and then continuing  Waiting and then being notified  Ben Abdallah Helmi Architect J2EE
  • 8. Yielding A thread can offer to move out of the virtual CPU by yielding.  The yield() method is a static method of the Thread class. It always causes the currently executing thread to yield.  Yielding allows a time-consuming thread to permit other threads to execute.  Ben Abdallah Helmi Architect J2EE
  • 9. Suspending  The exact effect of suspend() and resume() is much better implemented using wait() and notify(). Ben Abdallah Helmi Architect J2EE
  • 10. Sleeping A sleeping thread passes time without doing anything and without using the CPU.  public static void sleep(long milliseconds) throws InterruptedException Or public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException  The Thread class has a method called interrupt(). A sleeping thread that receives an interrupt() call moves immediately into the Ready state; when it gets to run, it will execute its InterruptedException handler  Ben Abdallah Helmi Architect J2EE
  • 11. Blocking Many methods that perform input or output have to wait for some occurrence in the outside world before they can proceed; this behavior is known as blocking. A good example is reading from a socket: 1. try { 2. Socket sock = new Socket(“magnesium”, 5505); 3. InputStream istr = sock.getInputStream(); 4. int b = istr.read(); 5. } 6. catch (IOException ex) { 7. // Handle the exception 8. } Ben Abdallah Helmi Architect J2EE
  • 12. Monitor States The wait() method puts an executing thread into the Waiting state, and the notify() and notifyAll() methods move waiting threads out of the Waiting state. However, these methods are very different from suspend(), resume(), and yield(). For one thing, they are implemented in the Object class, not in Thread. For another, they can be called only in synchronized code Ben Abdallah Helmi Architect J2EE
  • 13. Java’s monitor support addresses these issues by providing the following resources:  A lock for each object  The synchronized keyword for accessing an object’s lock  The wait(), notify(), and notifyAll() methods, which allow the object to control client threads  Ben Abdallah Helmi Architect J2EE
  • 14. The Object Lock and Synchronization  Every object has a lock. At any moment, that lock is controlled by, at most, one single thread. The lock controls access to the object’s synchronized code. A thread that wants to execute an object’s synchronized code must first attempt to acquire that object’s lock. If the lock is available— that is, if it is not already controlled by another thread—then all is well. If the lock is under another thread’s control, then the attempting thread goes into the Seeking Lock state and becomes ready only when the lock becomes available. When a thread that owns a lock passes out of the synchronized code, the thread automatically gives up the lock. All this lockchecking and state-changing is done behind the scenes; the only explicit programming you need to do is to declare code to be synchronized. Ben Abdallah Helmi Architect J2EE
  • 15. wait() and notify()  The wait() and notify() methods provide a way for a shared object to pause a thread when it becomes unavailable to that thread and to allow the thread to continue when appropriate. The threads themselves never have to check the state of the shared object. Ben Abdallah Helmi Architect J2EE
  • 16.  Both wait() and notify() must be called in synchronized code. A thread that calls wait() releases the virtual CPU; at the same time, it releases the lock. It enters a pool of waiting threads, which is managed by the object whose wait() method got called. Every object has such a pool. Ben Abdallah Helmi Architect J2EE
  • 17. 1. public synchronized String retrieveMessage() { 2. while (request == false) { 3. try { 4. wait(); 5. } catch (InterruptedException e) { } 6. } 7. request = false; 8. return message; 9. } 1. public synchronized void 2. storeMessage(String message) { 3. this.message = message; 4. request = true; 5. notify(); 6. } The notify() method rbitrarily selects one of the threads in the monitor’s waiting pool and moves it to the Seeking Lock state. Eventually that thread will acquire the mailbox’s lock and can proceed with execution. Ben Abdallah Helmi Architect J2EE
  • 18.        Here are the main points to remember about wait(): The calling thread gives up the CPU. The calling thread gives up the lock. The calling thread goes into the monitor’s waiting pool. Here are the main points to remember about notify(): One arbitrarily chosen thread gets moved out of the monitor’s waiting pool and into the Seeking Lock state. The thread that was notified must reacquire the monitor’s lock before it can proceed. Ben Abdallah Helmi Architect J2EE
  • 19. The Class Lock It is clear by now that every object (that is, every instance of every class) has a lock. Every class also has a lock. The class lock controls access to all synchronized static code in the class. Consider the following example: class X { static int x, y; static synchronized void foo() { x++; y++; } Ben Abdallah Helmi Architect J2EE }
  • 20. notifyAll(): Always check the monitor’s state in a while loop rather than an if statement. After changing the monitor’s state, call notifyAll() rather than notify(). 1. public synchronized void mixedUpMethod() { 2. if (i<16 || f>4.3f || message.equals(“UHOH”) { 3. try { wait(); } catch (InterruptedException e) { } 4. } 5. 6. // Proceed in a way that changes state, and then... 7. notify(); 8. } 1. public synchronized void mixedUpMethod() { 2. while (i<16 || f>4.3f || message.equals(“UHOH”) { 3. try { wait(); } catch (InterruptedException e) { } 4. } 5. 6. // Proceed in a way that changes state, and then... 7. notifyAll(); 8. } Ben Abdallah Helmi Architect J2EE
  • 21. Synchronizing Part of a Method 1. class StrangeSync { 2. Rectangle rect = new Rectangle(11, 13, 1100, 1300 ); 3. void doit() { 4. int x = 504; 5. int y = x / 3; 6. rect.width -= x; 7. rect.height -= y; 8. } 9. } perhaps you want to synchronize only lines 6 and 7, and perhaps you want a thread attempting to execute those lines to synchronize on the lock of rect, rather than on the lock of the current executing object. The way to do this is shown here: 1. class StrangeSync { 2. Rectangle rect = new Rectangle(11, 13, 1100, 1300 ); 3. void doit() { 4. int x = 504; 5. int y = x / 3; 6. synchronized(rect) { 7. rect.width -= x; 8. rect.height -= y; 9. } 10. } 11. } Ben Abdallah Helmi Architect J2EE
  • 22.    To synchronize an entire method, using the lock of the object that owns the method. To do this, put the synchronized keyword in the method’s declaration. To synchronize part of a method, using the lock of an arbitrary object. Put curly brackets around the code to be synchronized, preceded by synchronized(theArbitraryObject). To synchronize part of a method, using the lock of the object that owns the method. Put curly brackets around the code to be synchronized, preceded by synchronized(this). Ben Abdallah Helmi Architect J2EE