Nothing Special   »   [go: up one dir, main page]

Advanced Java Cha 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

Multithreading in java

Chapter three

1
Objectives
 What are Threads?
 Interrupting threads
 Thread properties
 Threads priorities
 Synchronization
 Threads and Swing

2
 What are Threads?
 The smallest unit of executable code

that performs a particular task.


• An application can be divided into multiple

tasks and each task can be assigned to a


thread.
 Many threads executing simultaneously

is termed as Multithreading.
• Appears that the processes are running

concurrently, but it isn’t so.

3
 When Java programs execute, there is
always one thread running and that is the
main thread.
• It is this thread from which child threads

are created.
• Program is terminated when main thread

stops execution.
• Main thread can be controlled through

Thread objects.
• Reference of the main thread can be

obtained by calling the currentThread()


method of the Thread class.
4
 Why Multithreading?
 Increases performance of single-processor
system, as it reduces the CPU idle time.
 Multithreading encourages faster execution of

a program
 Multithreading introduces the concept of

parallel processing

5
 Creating Thread
 Two ways:
1. Declare a class that is a sub-class of the
class Thread defined in java.lang
package:

class mythread extends Thread


2. Declare a class that implements the
Runnable interface (recommended):

class mythread implements Runnable


6
 Creating Thread

We should implement Runnable because we


could extend another class and share object
Tips: Java allows single inheritance only

7
 Creating Thread

1. Override run method of Thread class.


2. The code inside is the task assign to
thread when running.

8
 Creating Thread

1. Implement the runnable interface.


2. The code inside is the task assign to
thread when running.

9
 Running Thread
 After a new thread has been initiated, we use
the start() method to start the thread
 Otherwise it is an empty Thread object with no

system resources allocated.

 When start() method is invoked, the system


resources required to run the thread are
created and schedules the thread to run.
 It then calls the thread’s run() method.
10
 Running Thread

Output

11
Thread States
– New
– Runnable
– Blocked
– Dead

12
Thread Properties

13
Thread Properties

Pause for a while for


another thread run

14
Thread Properties

Pause for a while for


another thread run

15
 Thread Properties

Output

16
 Methods of Thread class

• getName() and setName()


• start() – a thread object is in a runnable state
• run() – is executed once the start method is
invoked
• sleep() – suspends the execution of the current
thread for a specified period of time

17
Methods of Thread class …
• setPriority() and getPriority()
 The constants :
NORM_PRIORITY – value is 5 (default)
MAX_PRIORITY – value is 10
MIN_PRIORITY – value is 1
• Priorities for carrying out activities changes at
times.
• We may have to run a thread of higher
importance without stopping or suspending the
current running thread.
• Thread priorities play an important role in such a

situation.
18
 Methods of Thread class …
• The highest-priority runnable thread keeps
running until:
– It yields by calling the yield() method
– It ceases to be runnable (either by dying or
by entering the blocked state)
– A higher-priority thread has become
runnable.
• We can use follow method to set priority of
Thread
void setPriority(int newP)

19
Types of Threads
• Two types of threads in Java:
1. User threads:
• Created by the user
2. Daemon threads:
• Threads that work in the background
providing service to other threads
(e.g. – the garbage collector thread)

20
Types of Threads …
• When user thread exits, JVM checks to
find out if any other thread is running.
– If there are, it will schedule the next
thread.
– If the only executing threads are
daemon threads, it exits.
• We can set a thread to be a Daemon if we
do not want the main program to wait until
a thread ends.
• isDaemon(), setDaemon(true)
21
• “isAlive()" Method
– Use to find out whether a specific thread is
running or not.
• “join()" Method
– Causes the current thread to wait until the thread
on which it is called terminates.
– Allows specifying the maximum amount of time
that the program should wait for the particular
thread to terminate.
– It throws InterruptedException if another thread
interrupts it.
– The calling thread waits until the specified thread
terminates.
22
 Interrupting Thread
• There is no longer a way to force a thread
to terminate.
• The interrupt method can be used to
request termination of a thread.
• Checking one thread is interrupted:
Thread.currentThread().isInterrupted() 
• If a thread is blocked, it cannot check the
interrupted status. This is where the
InterruptedException comes in.

23
 Interrupting Thread
public void run()
{ Pattern for interrupting a thread
try{ . . .
while (more work to do){
do more work
}
}
catch(InterruptedException exception){
// thread was interrupted during sleep or wait
}
finally{
cleanup, if required
}
// exit run method and terminate thread
}
24
Thread Synchronization
• What happens if two threads have access to
the same object and each calls a method
that modifies the state of the object?
• In such a case, data may become
inconsistent.
• Situation is often called a race condition.
• To avoid simultaneous access of a shared
object by multiple threads, you must learn
how to synchronize the access.

25
Thread Synchronization - 1st approach
• Thread Communication Without Synchronization
Bank example
• There are some things wrong.
• The Race Condition :
– The problem is that these are not atomic
operations.
– The real problem is that the work of the
transfer method can be interrupted in the
middle. If we could ensure that the method
runs to completion before the thread loses
control, then the state of the bank account
object would not be corrupted.
26
Thread Synchronization - 1st approach …

27
Thread Synchronization - 1st approach …
• Synchronization is based on the concept of
monitor.
– A monitor is an object that is used as a mutually
exclusive lock.
• Only one thread can enter a monitor:
– When one thread enters the monitor, it means that the
thread has acquired a lock
– All other threads must wait till that thread exits the
monitor.
• For a thread to enter the monitor of an object:
– The programmer may invoke a method created using
the synchronized keyword (implicit synchronize).
– Or using explicit lock objects.
28
Thread Synchronization - 1st approach …
– Simply tag any operation that should not be
interrupted as synchronized, for example :
public synchronized void transfer
(int from, int to, int amount)
– When one thread calls a synchronized
method, it is guaranteed that the method will
finish before another thread can execute any
synchronized method on the same object.

29
Thread Synchronization - 1st approach…

30
Thread Synchronization - 1st approach…
• When a thread calls a synchronized method,
the object becomes "locked."
• Periodically, the thread scheduler activates the
threads that are waiting for the lock to open.
• Other threads are still free to call
unsynchronized methods on a locked object.
• When a thread leaves a synchronized method
by throwing an exception, it relinquishes the
object lock.

31
Thread Synchronization - 1st approach…
• If a thread owns the lock of an object and it
calls another synchronized method of the
same object, then that method is
automatically granted access. The thread only
relinquishes the lock when it exits the last
synchronized method.

32
Thread Synchronization - 1st approach…
This mechanism ensures that there is a smooth
transition of a particular resource between two
competitive threads.
It also oversees the condition in a program where
one thread is:
Allowed to wait for the lock.
Notified to end its waiting state and get the lock
When a thread executes a call to wait, it surrenders
the object lock and enters a wait list for that object.
To remove a thread from the wait list, some other
thread must make a call to notifyAll or notify, on the
same object.

33
Thread Synchronization - 1st approach …
notify() First thread

notify()
wakes up or
notifies the
first thread.

notifyAll() Thread 2
notifyAll()
wakes up or Thread 1
notifies all the
Thread 3
threads that
called wait( ) on
the same object. Java Simplified / Session 16 / 34 of 32

34
Thread Synchronization - 1st approach …
– Syntax : synchronized (object){
//do your work
}
– Example :
public void run(){
try
{
while (true)
{
synchronized (bank) {
//do your work
}
}
}
catch (InterruptedException e) {}
}
35
Thread Synchronization - 1st approach …
 If one thread calls a synchronized static
method of a class, all synchronized
static methods of the class are blocked
until the first call returns.

 Example :
public static synchronized getInstance()

36
Thread Synchronization – 2nd approach
• The basic outline for protecting a code block with a
ReentrantLock is:
private Lock bankLock;
private Condition sufficientFunds;
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();
bankLock.lock();
try {
while (accounts[from] < amount)
sufficientFunds.await();
sufficientFunds.signalAll();
}
finally{
bankLock.unlock();
}
37
Thread Synchronization – 2nd approach …
• This construct guarantees that only one
thread at a time can enter the critical section.
• As soon as one thread locks the lock object, no
other thread can get past the lock statement.
• When other threads call lock, they are blocked
until the first thread unlocks the lock object.

38
Thread Synchronization – 2nd approach …
Condition Objects
 See code below:
if (bank.getBalance(from) >= amount)
bank.transfer(from, to, amount);
 It is entirely possible that the current thread will be
deactivated between the successful outcome of the test
and the call to transfer:
if (bank.getBalance(from) >= amount)
// thread might be deactivated at this point
bank.transfer(from, to, amount);
 By the time the thread is running again, the account
balance may have fallen below the withdrawal amount.

39
Thread Synchronization – 2nd approach …
Condition Objects

40
Thread Synchronization – 2nd approach …
Condition Objects
• What do we do when there is not enough
money in the account?
• We wait until some other thread has added
funds. But this thread has just gained exclusive
access to the bankLock, so no other thread
can have a chance to make a deposit.
• The solution is : condition objects
– A lock object can have one or more
associated condition objects.

41
Thread Synchronization – 2nd approach …
Condition Objects

42
Thread Synchronization – 2nd approach …
Condition Objects

• If the Transfer method finds that sufficient


funds are not available, it calls

=>The current thread is now blocked and gives


up the lock. This lets in another thread that can,
we hope, increase the account balance

43
Thread Synchronization – 2nd approach …
Condition Objects
• There is an essential difference between a
thread that is waiting to acquire a lock and a
thread that has called await.
• Once a thread calls the await method, it
enters a wait set for that condition.
• Even though the lock is available, the thread is
still blocked.
• So, it stays blocked until another thread has
called the signalAll method on the same
condition.
44
Thread Synchronization – 2nd approach …
Condition Objects
• The signalAll method call unblocks all threads
that are waiting for the condition.
• When the threads are removed from the wait
set, they are again runnable and the scheduler
will eventually activate them again.

45
Thread Synchronization – 2nd approach…
Fairness
• A fair lock favors the thread that has been
waiting for the longest time.
• By default, locks are not required to be fair.
• You can specify that you want a fair locking
policy:
Lock fairLock = new ReentrantLock(true);

• Fair locks are a lot slower than regular locks.


• You should only enable fair locking if you have a
specific reason why fairness is essential for your
problem.
46
Thread Synchronization – 2nd approach …
Fairness
• The tryLock method tries to acquire a lock and
returns true if it was successful. Otherwise, it
immediately returns false.

• You can call tryLock with a timeout parameter, like


this:
if(myLock.tryLock(100, TimeUnit.MILLISECONDS))

• TimeUnit is an enumeration with values SECONDS,


MILLISECONDS, MICROSECONDS, and NANOSECONDS.
47
Deadlocks
Analyzing following situation

48
Deadlocks …
• If all threads in an application are blocked. The
system has deadlocked.
• Unfortunately, there is nothing in the Java
programming language to avoid or break these
deadlocks.
• You must design your threads to ensure that a
deadlock situation cannot occur.
• Notify/notifyAll method can unblock thread(s).

49
 Threads and Swing

50
 Threads and Swing

51
Thank you

52

You might also like