Java-Threads&SynchF
Java-Threads&SynchF
Agenda
◼ Introduction
◼ Exploring Threads
◼ Sharing Resources
◼ Inter-Thread Communication
◼ Deadlock
◼ Advanced Issues
◼ Assignment
Introduction
◼ Definition
◼ Motivation
◼ Process
◼ Java Thread Memory Model
◼ Threads compared with Processes
Definition
◼ Objects provide a way to divide a program into independent
sections. Often, you also need to turn a program into separate,
independently running subtasks.
Each of these independent subtasks is called a thread.
Which to choose:
◼ If you extend the Thread Class, that means that subclass
cannot extend any other Class, but if you implement Runnable
interface then you can do this.
◼ And the class implementing the Runnable interface can avoid
the full overhead of Thread class which can be excessive.
◼ Else use Thread
Thread Methods
• Start: a thread by calling start its run method
• Sleep: suspend a thread fora period of time
• Run: entry-point for a thread
• Join: wait for a thread to terminate
• isAlive: determine if a thread is still running
• getPriority: obtain a thread’s priority
• getName:obtain a thread’s name
Priority
◼ The priority of a thread tells the scheduler how
important this thread is.
◼ The thread scheduler can use the thread priorities
to determine the execution schedule of threads.
◼ Priorities are integer values
◼ Thread.MIN_PRIORITY: 1
◼ Thread.MAX_PRIORITY: 10
◼ Thread.NORM_PRIORITY: 5
Joining
◼ One thread may call join( ) on another thread to
wait for the second thread to complete before
proceeding.
Yielding
◼ Causes the currently executing thread to pause and
allow other threads to execute.
◼ This hint (and it is a hint—there’s no guarantee your
implementation will listen to it) takes the form of the
yield() method.
◼ In general, yield() is useful only in rare situations
and you can’t rely on it to do any serious tuning of
your application
Sleeping
◼ Causes the currently executing thread to pause for a given
number of milliseconds.
◼ When you call sleep( ), it must be placed inside a try block
because it’s possible for sleep( ) to be interrupted before it
times out.
◼ It just stops the execution of the thread for a while.
◼ There is no guaranty that thread will resume the execution after
the given number of milliseconds.
◼ Not to use in real-time application.
Interrupting
◼ Interruption is a mechanism whereby a thread that is waiting
(or sleeping) can be made to prematurely stop waiting.
◼ Volatile Variable: Every time the variable is used it must be read from
main memory. Similarly, every time the variable is written, the value
must be stored in main memory.
Synchronization (Cont…)
◼ Only methods (or blocks) can be synchronized, Classes and variable
cannot be synchronized.