0% found this document useful (0 votes)
39 views

Brigola, Kenneth Chu, Carmina Madrid, Claudine Navarro, Vincent Reganit, Annalyn Sta. Maria, Maricone

Threads are lightweight processes that allow Java programs to take advantage of multiprocessor systems and perform background tasks. Creating threads involves extending the Thread class or using Thread constructors. Threads must be started and ended properly to avoid errors. Shared data accessed by multiple threads must be synchronized to avoid inconsistencies. Overuse of threads can harm performance and maintainability.

Uploaded by

marciapuffstone
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Brigola, Kenneth Chu, Carmina Madrid, Claudine Navarro, Vincent Reganit, Annalyn Sta. Maria, Maricone

Threads are lightweight processes that allow Java programs to take advantage of multiprocessor systems and perform background tasks. Creating threads involves extending the Thread class or using Thread constructors. Threads must be started and ended properly to avoid errors. Shared data accessed by multiple threads must be synchronized to avoid inconsistencies. Overuse of threads can harm performance and maintainability.

Uploaded by

marciapuffstone
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Brigola, Kenneth

Chu, Carmina
Madrid, Claudine
Navarro, Vincent
Reganit, Annalyn
Sta. Maria, Maricone
What are threads?

 Referred to as lightweight processes.


 The Java thread facility is simple. However,
complex programs that use threading
effectively is not quite simple.
 Every Java program uses at least on
thread – the main thread.
 JVM creates threads that are mostly
invisible to you.
Reasons for using threads:

 Make UI more responsive


 Take advantage of multiprocessor
systems
 Simplify modelling
 Perform background processing
Risks to avoid

 When multiple threads access same data


item, make sure that they coordinate their
access to the data so that both see a
consistent view of the data and neither
steps on the other’s changes.
 When accessing variables from more than
one thread, make sure that access is
properly synchronized.
 If you are going to use synchronization to
protect access variables, make sure to use
it everywhere in your program where the
variable is accessed.
Do not overuse it

 Overuse of threads can be hazardous to


your program’s performance and
maintainability.
 Multiple threads will not make a CPU-
bound program run any faster on a
single-processor system.
Creating threads

 Threads are created through the


Thread constructors or by instantiating
classes that extend from the Thread
class.
 Two kinds of Threads:
The actual thread
The running thread created by the
operating system.
Creating threads and starting threads are not
the same
 A thread doesn't actually begin to
execute until another thread calls the
start() method on the Thread object
for the new thread. The Thread object
exists before its thread actually starts,
and it continues to exist after its thread
exits.
Ending Threads

 The thread comes to the end of its


run() method. The thread throws an
Exception or Error that is not caught.
 Another thread calls one of the
deprecated stop() methods.
Deprecated means they still exist, but
you shouldn't use them in new code and
should strive to eliminate them in
existing code.
Joining Threads
 The thread that invoked join() will block
until the target thread completes.
 Thread.join() is generally used by
programs that use threads to partition
large problems into smaller ones, giving
each thread a piece of the problem. The
example at the end of this section creates
ten threads, starts them, then uses
Thread.join() to wait for them all to
complete.
Scheduling
public class TwoThreads {

public static class Thread1 extends Thread {


public void run() {
System.out.println("A");
System.out.println("B");
}
}

public static class Thread2 extends Thread {


public void run() {
System.out.println("1");
System.out.println("2");
}
}
 Possible Output:
 12AB
public static void main(String[] args) {
 1A2B new Thread1().start();
 1AB2 new Thread2().start();
 A12B }
 A1B2
}
 AB12
 Output varies from machine to machine and even running the program
multiple times in a machine but “1” will always go first before ”2” and “A”
before “B”.
Sleeping

 sleep() will cause the current thread to go


into a wait state until the specified amount of
time has elapsed or until the thread is
interrupted by another thread calling
Thread.interrupt().
 yield() method is like sleep(), but instead
of sleeping, it simply pauses the current thread
momentarily so that other threads can run. In
most implementations, threads with lower
priority will not run when a thread of higher
priority calls yield().
Daemon threads

 They are service providers for other


threads running in the same process as
the daemon thread.
 You might want to use daemon threads
for background threads that you create
in your programs, such as timer threads
or other deferred event threads, which
are only useful while there are other
non-daemon threads running.
AWT and Swing

 Creates a single thread for handling


UI events, and any event listeners
 AWT events execute in the AWT
event thread
 Not a daemon thread.
 Ends with System.exit();
 Synchronizing access to data items shared
between event listeners and other threads
 Find a way for long-running tasks triggered
by event listeners , like checking spelling in
a large document or searching a file
system for a file -- to run in a background
thread so the UI doesn't freeze while the
task is running. (prevent the user from
canceling the operation)
Timer Task

 Introduced to the Java language in JDK 1.3


 Daemon thread
 Allows you to execute a task at a later time
or to execute a task periodically
 Implementing is quite straightforward: it
creates a timer thread and builds a queue
of waiting events sorted by execution time.
 Properly synchronized
Servlets and JavaServer Pages technology

 Create multiple threads


 Assume at all times that the same
servlet or JSP file may be executing
concurrently in multiple threads
 Must be appropriately synchronized,
includes fields of the servlet object
itself
RMI - Remote Method Invocation

 Allows you to invoke operations on objects


running in other JVMs
 To implement an RMI object is to extend a
class from UnicastRemoteObject
 The infrastructure for dispatching remote
method calls is initialized. This includes a
socket listener to receive remote invocation
requests, and one or more threads to
execute remote requests.
Sharing variables

 For multiple threads to be useful in a


program, they have to have some way to
communicate or share their results with
each other.
 The Java language provides two keywords
for ensuring that data can be shared
between threads in a controlled manner:
synchronized and volatile
Synchronized

 Synchronized has two important meanings:


 it ensures that only one thread executes a
protected section of code at one time (mutual
exclusion or mutex)
 it ensures that data changed by one thread is
visible to other threads (visibility of changes).
 Without synchronization, it is easy for data to be left in
an Inconsistent state.
 Synchronization allows us to define blocks of code
that must run atomically, in which they appear to
execute in an all-or-nothing manner, as far as other
threads can tell.
Volatile

 Volatile is simpler than synchronization and is


suitable only for controlling access to single
instances of primitive variables -- integers,
booleans, and so on.
 When a variable is declared volatile, any write to
that variable will go directly to main memory,
bypassing the cache, while any read of that
variable will come directly from main memory,
bypassing the cache.
 This means that all threads see the same value
for a volatile variable at all times.
Atomic code blocks protected by locks

 Every Java object has an associated


lock.
 Java locks can be held by no more
than one thread at a time. When a
thread enters a synchronized block of
code, the thread blocks and waits until
the lock is available, acquires the lock
when it becomes available, and then
executes the block of code.
Synchronization example
public class SyncExample {
private static lockObject = new Object();
private static class Thread1 extends Thread {
public void run() {
synchronized (lockObject) {
x = y = 0;
System.out.println(x);
}
}
}
private static class Thread2 extends Thread {
public void run() {
synchronized (lockObject) {
x = y = 1;
System.out.println(y);
}
}
}
public static void main(String[] args) {
new Thread1().run();
new Thread2().run();
}
}
 Using synchronized blocks allows you to perform a group of related
updates as a set without worrying about other threads interrupting or
seeing the intermediate results of a computation. The example code
will either print "1 0" or "0 1." In the absence of synchronization, it
could also print "1 1" (or even "0 0," believe it or not).
 Because the timing of thread execution
is nondeterministic, we need to be
careful to control a thread's access to
shared data. Otherwise, multiple
concurrent threads could step on each
other's changes and result in corrupted
data, or changes to shared data might
not be made visible to other threads on
a timely basis.
Mutual Exclusion

 In Sharing access to data, we discussed the


characteristics of synchronized blocks and
described them as implementing a classic mutex
in which only one thread can execute a block
protected by a given lock at one time.
 Mutual exclusion is an important part of what
synchronization does, but synchronization also
has several other characteristics important to
achieve correct results on multiprocessor systems.
Visibility

 In addition to mutual exclusion, synchronization,


like volatile, enforces certain visibility constraints.
When an object acquires a lock, it first invalidates
its cache, so that it is guaranteed to load variables
directly from main memory.
 Similarly, before an object releases a lock, it
flushes its cache, forcing any changes made to
appear in main memory.
 In this way, two threads that synchronize on the
same lock are guaranteed to see the same values
in variables modified inside a synchronized block.
When do you have to synchronize?

 To maintain proper visibility across threads, you


have to use synchronized (or volatile) to ensure
that changes made by one thread are visible by
another whenever a non-final variable is shared
among several threads.
 The basic rule for synchronizing for visibility is that
you must synchronize whenever you are:
Reading a variable that may have been last
written by another thread
 Writing a variable that may be read next by
another thread
Synchronization for consistency

 In addition to synchronizing for visibility, you must


also synchronize to ensure that consistency is
maintained from an application perspective.
 When modifying multiple related values, you want
other threads to see that set of changes atomically
-- either all of the changes or none of them.
 Consider the following example, which implements a
simple (but not thread-safe) stack of integers:

public class UnsafeStack {


public int top = 0;
public int[] values = new int[1000];
public void push(int n) {
values[top++] = n;
}
public int pop() {
return values[--top];
}
 In this case,
} the solution is simple: synchronize both push()
and pop(), and you'll prevent one thread from stepping on
another.
Immutability and final fields

 Many Java classes, including String, Integer,


and BigDecimal, are immutable: once
constructed, their state never changes. A class
would be immutable if all of its fields were declared
final.
 Similarly, final fields are also more thread-friendly.
Because final fields cannot change their value
once initialized, you do not need to synchronize
access when sharing final fields across threads.
When you don't need to synchronize

 There are a few cases where you do not have to


synchronize to propagate data from one thread to
another, because the JVM is implicitly performing
the synchronization for you.
 These cases include:
When data is initialized by a static initializer
When accessing final fields
When an object is created before a thread is
created
When an object is already visible to a thread
that it is then joined with
Deadlock

 A set of processes or threads is said to be


deadlocked when each is waiting for an action that
only one of the others can perform.
 To avoid deadlock, you should ensure that when
you acquire multiple locks, you always acquire the
locks in the same order in all threads.
Guidelines for synchronization

 There are a few simple guidelines you can follow when writing
synchronized blocks that will go a long way toward helping you
to avoid the risks of deadlock and performance hazards:
 Keep blocks short. Synchronized blocks should be short
-- as short as possible while still protecting the integrity of
related data operations. Move thread-invariant preprocessing
and postprocessing out of synchronized blocks.
 Don't block. Don't ever call a method that might block,
such as InputStream.read(), inside a synchronized block
or method.
 Don't invoke methods on other objects while holding a
lock. This may sound extreme, but it eliminates the most
common source of deadlock.
wait(), notify(), notifyAll() methods

 wait( ) tells the calling thread to give


up the monitor and go to sleep until
some other thread enters the same
monitor and calls notify( ).
 notify( ) wakes up the first thread that
called wait( ) on the same object.
 notifyAll( ) wakes up all the threads
that called wait( ) on the same object.
The highest priority thread will run first.
Thread priorities

 Syntax:
<thread>.setPriority(<priority>);
 Priorities:
Thread.MIN_PRIORITY
○ Has integer value 1.
Thread.NORM_PRIORITY
○ Has integer value 5.
Thread.MAX_PRIORITY
○ Has integer value 10.
Thread Groups

 The ThreadGroup class was originally


intended to be useful in structuring
collections of threads into groups.
However, it turns out that ThreadGroup is
not all that useful. You are better off
simply using the equivalent methods in
Thread.
Swing Utilities

 Swing applications have a single UI thread


(sometimes called the event thread) in which all UI
activity must occur. Sometimes another thread may
want to update the appearance of something on
the screen or fire an event on a Swing object.
 The SwingUtilities.invokeLater() method
allows you to pass a Runnable object to it, and the
specified Runnable will be executed in the event
thread. Its cousin, invokeAndWait(), will invoke
Runnable in the event thread, but invokeAndWait()
will block until Runnable is finished executing.

You might also like