Java Thread
Java Thread
DEVELOPMENT PROGRAM
Thread
OUTLINE
• Thread & Process
• Thread in Java
• Thread
• Runnable
• Daemon Threads
• Synchronization
• Thread problem
PROCESS
• A process has a self-contained execution environment.
• However, what the user sees as a single application may in fact be a set
of cooperating processes
• When extending the Thread class, we're not overriding any of its methods. Instead,
we override the method of Runnable (which Thread happens to implement).
This is a clear violation of IS-A Thread principle
• After extending the Thread class, we can't extend any other class
• t
causes the current thread to pause execution until 's thread terminates. Overloads of join allow the
programmer to specify a waiting period.
• However, as with sleep, join is dependent on the OS for timing, so you should not assume
that join will wait exactly as long as you specify.
THREAD EXAMPLE
• SimpleThreads
• Create a daemon thread for functionalities that are not critical to system
• Imagine you're writing a simple game where your main method loops until
you decide to quit. And imagine that at the start of the game, you start a
thread that will endlessly poll some website to trigger alerts. You would like
the JVM to exit when you decide to end the game. You don't want the
endless polling to prevent the game from ending. So you make this polling
thread a daemon thread.
THREAD INTERFERENCE
• Consider a situation where
two thread is operating on the
same object at the same
time.
• 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.
THREAD INTERFERENCE
• Virtual Machines like JVM will
decompose the “c++” statement
into following steps
• Deadlock
• Starvation (Optional)
• Livelock (Optional)
DEADLOCK
• Deadlock describes a situation where two or more threads
are blocked forever, waiting for each other
STARVATION
• A situation where a thread is unable to gain regular
access to shared resources and is unable to make
progress