Вы находитесь на странице: 1из 40

1

TCS Confidential
Threads, Applets and
Event Handling
2
TCS Confidential
Threads
Thread Basics
Why use Threads
Java Thread Model
States of Thread
Threads Life
Scheduling, Joining threads
Threads interference bugs
Synchronizing using monitors
Deadlock
3
TCS Confidential
Thread basics
Concurrent Programming
A single application is often expected to
do more than one thing at a time; e.g.
streaming audio application.
In concurrent programming, there are
two basic units of execution: processes
and threads.
4
TCS Confidential
Thread basics
Process
A process has a self-contained
execution environment.
It has private set of basic run-time
resources; in particular, each
process has its own memory
space.
5
TCS Confidential
Thread basics
Threads
Called lightweight processes.
Provides an execution environment.
Creating a new thread requires
fewer resources than creating a new
process.
6
TCS Confidential
Thread basics
Threads vs. Processes
Threads exist within a process
every process has at least one.
Threads share process's resources,
including memory and open files.
Threads provides efficient, but
potentially problematic,
communication.
7
TCS Confidential
Why use threads ?
Make UI more responsive
Perform background processing
Simplify modeling
Take advantage of multiprocessor
systems
8
TCS Confidential
The Java Thread Model
Mutlithreaded program contains
two or more parts that can run
concurrently.
Each part of such a program is
called a thread.
Each thread defines a separate
path of execution.
9
TCS Confidential
The Java Thread Model
A thread is the smallest unit of
dispatchable code.
In process-based multitasking, a
program is the smallest unit of code
that can be dispatched by the
scheduler. Thus, multithreading is a
specialized form of multitasking.
10
TCS Confidential
The States of Threads
Running
Running
Ready to run
Ready to run
A thread
Terminated
at any time
A thread
Terminated
at any time
Suspended
Suspended
Blocked
Resumed
When a Java program starts, there is only the main
thread running. All child threads are spawned from
the main thread. On termination of the main thread,
the program itself terminates.
11
TCS Confidential
Creating a thread
Starting a thread calls run()
method
Ending a thread
Joining with Threads
Scheduling
Sleeping
Threads Life
12
TCS Confidential
Java defines two ways of creating
threads:
extend the Thread class itself.
implement the Runnable
interface.
Creating Threads
13
TCS Confidential
Creating Threads
Every Java program contains at
least one thread: the main thread.
Additional threads are created
through the Thread constructor or
by instantiating classes that extend
the Thread class.
14
TCS Confidential
Creating Threads
The running thread is generally
created by the operating system;
the Thread object is created by the
Java VM as a means of controlling
the associated thread.
15
TCS Confidential
Example of Java Thread program
Example (PrimeThread.java):
Calculate and display prime numbers
starting from 15 up to < 50.
16
TCS Confidential
Starting Threads
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.
17
TCS Confidential
Ending Threads
A thread will end in one of the two
ways:
The thread comes to the end of its
run() method.
The thread throws an Exception or
Error that is not caught.
Note: When all the threads within a
Java program complete, the program
exits.
18
TCS Confidential
Joining, Scheduling & Sleeping Threads
Joining with threads
The Thread API contains a method for
waiting for another thread to complete: the
join( ) method.
Scheduling
Except when using Thread.join() and
Object.wait(), the timing of thread scheduling
and execution is nondeterministic.
19
TCS Confidential
Example of Thread Scheduling
Example:
Create and start two threads, each of
which prints two lines to System.out
Check the thread scheduling.
We have no idea in what order the lines will
execute, except that "1" will be printed before "2
" and "A" before "B." The output could be any
one of the following:
1 2 A B
1 A 2 B
1 A B 2
A 1 2 B
20
TCS Confidential
Joining, Scheduling & Sleeping Threads
Sleep
Thread API : sleep (long millis)
Current thread goes into a wait state
until the specified amount of time has
elapsed or until the thread is
interrupted
21
TCS Confidential
Joining, Scheduling & Sleeping Threads
When the specified time elapses, the
thread again becomes runnable and
goes back onto the scheduler's queue
of runnable threads.
22
TCS Confidential
Joining, Scheduling & Sleeping Threads
Daemon threads
System threads are called daemon
threads
Java program actually exits when all
its non-daemon threads have
completed
A thread is marked as daemon by
calling the setDaemon (true)
23
TCS Confidential
Sharing access to data
A thread shares the same process
context, including memory, with
other threads in the same process.
Can access shared variables (static
or instance fields)
24
TCS Confidential
Sharing access to data
Threads must ensure that they access
shared variables in a controlled
manner, else there will be thread
interference bugs in application.
25
TCS Confidential
Thread Interference Bugs
Thread Interference Example
Consider a simple class called Counter
class Counter {
private int count = 0;
public void increment() { count ++; }
public void decrement() { count --; }
public int value() { return count; }
}
26
TCS Confidential
Thread Interference Bugs
Interference happens when two
operations, running in different
threads, but acting on the same
data, interleave.
This means that the two operations
consist of multiple steps, and the
sequences of steps overlap.
27
TCS Confidential
Thread Interference Bugs
The single expression count++ can be
decomposed into 3 steps:
Retrieve the current value of count.
Increment the retrieved value by 1.
Store the incremented value back in
count.
Expression count -- can also be
decomposed the same way.
28
TCS Confidential
Thread Interference Bugs
Scenario:
Thread A invokes increment. At same time
Thread B invokes decrement. Say initial
value of count is 0, then their interleaved
actions might follow this sequence:
1. Thread A: Retrieve count.
2. Thread B: Retrieve count.
3. Thread A: Increment retrieved value;
result is 1.
29
TCS Confidential
Thread Interference Bugs
4. Thread B: Decrement retrieved value;
result is -1.
5. Thread A: Store result in count; count is
now 1.
6. Thread B: Store result in count; count is
now -1.
A's result is lost, overwritten by B.
Such bugs are difficult to detect and fix.
30
TCS Confidential
Solution to Thread Interference Bugs
The Java language provides two
keywords for ensuring that data can
be shared between threads in a
controlled manner: synchronized
and volatile.
31
TCS Confidential
Solution to Thread Interference Bugs
synchronized
Is used to protect access to larger
sections of code, such as sections
that involve updating multiple
variables.
It uses the concepts of monitors, or
locks, to coordinate access to
particular blocks of code.
32
TCS Confidential
Solution to Thread Interference Bugs
What is a lock ?
Every Java object has an
associated lock.
Java locks can be held by no more
than one thread at a time.
33
TCS Confidential
Solution to Thread Interference Bugs
When a thread enters a
synchronized block of code, it waits
until the lock is available, acquires
the lock when it becomes available,
and then executes the block of
code.
Thread releases the lock when
control exits the protected block of
code
34
TCS Confidential
Solution to Thread Interference Bugs
Counter Example modified
public class SynchronizedCounter {
private int count = 0;
public synchronized void increment() {
count ++; }
public synchronized void decrement() {
count --; }
public synchronized int value() {
return count; }}
35
TCS Confidential
Points to ponder on synchronized
If syncCounter is an instance of
SynchronizedCounter class, then
making these methods
synchronized has two effects:
First, it is not possible for two
invocations of synchronized
methods on the same object
(syncCounter) to interleave.
36
TCS Confidential
Points to ponder on synchronized
i.e. When one thread is executing a
synchronized method for an object,
all other threads that invoke
synchronized methods for the same
object block (suspend execution)
until the first thread is done with the
object.
37
TCS Confidential
Points to ponder on synchronized
Second, when a synchronized
method exits, it automatically
establishes a happens-before
relationship with any subsequent
invocation of a synchronized
method for the same object. This
guarantees that changes to the
state of the object are visible to all
threads.
38
TCS Confidential
Solution to Thread Interference Bugs
volatile
Is suitable only for controlling access to
single instances of primitive variables.
If 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.
So all threads see the same value for a
volatile variable at all times.
39
TCS Confidential
Deadlock in Multithreading
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.
The most common form of deadlock is
when Thread 1 holds a lock on Object A
and is waiting for the lock on Object B,
and Thread 2 holds the lock on Object
B and is waiting for the lock on Object
A.
40
TCS Confidential
Avoiding Deadlock condition
To avoid deadlock, you should
ensure that when you acquire
multiple locks, you always acquire
the locks in the same order in all
threads.

Вам также может понравиться