Java Threads - PowerPoint PPT Presentation

1 / 11
About This Presentation
Title:

Java Threads

Description:

An application is associated with an initial thread via a static void main method. ... 1) an object (inheriting Thread / conforming to Runnable) must be created. ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 12
Provided by: David58
Category:

less

Transcript and Presenter's Notes

Title: Java Threads


1
Java Threads
In Java processes are called threads.
An application is associated with an initial
thread via a static void main method.
Example
Thread.currentThread().sleep(100)
This statement causes the executing code to be
suspended for 100 milliseconds (0.1 sec.) (note
sleep is a static method.)
Additional threads are associated with objects.
Two steps are needed to execute a separate
thread
1) an object (inheriting Thread / conforming to
Runnable) must be created.
2) the method must be called
on the thread object.
2
public class Driver public static void
main(String args) MyThread threadA,
threadB threadA new MyThread()
threadA.start() threadB
new MyThread() threadB.start()
runAwhile() System.out.println("The
Driver thread is finished.")
public static void runAwhile() try
//delay for a random number of
millisec. Thread.currentThread().sleep
((int)(Math.random()1000)) catch
(InterruptedException e)
3
Example Thread Class
The Thread class is the superclass for creating
thread objects.
public class MyThread extends Thread
public void run() for (int j1
jlt5 j) System.out.println(Thre
ad.currentThread()" loop counter"j)
runAwhile() public
static void runAwhile() try
//delay for a random number of millisec.
Thread.currentThread().sleep((int)(Math.rand
om()1000)) catch (InterruptedExceptio
n e)
4
Sample Output
ThreadThread-0,5,main loop counter1 ThreadThre
ad-1,5,main loop counter1 ThreadThread-0,5,main
loop counter2 ThreadThread-0,5,main loop
counter3 The Driver thread is finished. ThreadTh
read-1,5,main loop counter2 ThreadThread-0,5,ma
in loop counter4 ThreadThread-1,5,main loop
counter3 ThreadThread-1,5,main loop
counter4 ThreadThread-0,5,main loop
counter5 ThreadThread-1,5,main loop counter5
public class Driver public static void
main(String args) MyThread threadA,
threadB threadA new MyThread()
threadA.start() threadB
new MyThread() threadB.start()
runAwhile() System.out.println("The
Driver thread is finished.")
public static void runAwhile() try
//delay for a random number of
millisec. Thread.currentThread().sleep
((int)(Math.random()1000)) catch
(InterruptedException e)
5
Thread Operations
sleep(int millisec) - from Thread
Suspend a process for the indicated number of
milliseconds.
start() - from Thread
Initiate the execution of a thread object,
concurrent with the executing thread. The new
thread executes its run() method.
Thread termination
A thread terminates when its run() method
completes execution.
wait() - from Object
Suspend the process in the waiting list
associated with the object.
notify() - from Object
Resume one process in the waiting list associated
with the object. (Note, this is different than a
signal - nothing occurs when no threads are
suspended.)
notifyAll() - from Object
Resume all processes in the waiting list
associated with the object.
yield() - from Thread
Causes this thread to allow other threads to
execute if they are suspended awaiting the object
this thread owns.
6
Thread States
7
Synchronization
Every Java object can be locked in one of two
ways
synchronized(objectRef) // the objectRef
object is locked for the duration of this
instruction. . . .
synchronized returnType someMethod (parmList)
// the this object is locked for the
duration of this method call. . . .
When a thread has locked an object, any other
thread attempting a lock will be suspended
(blocked) until the lock is released.
A synchronized instruction forms a critical
section.
synchronized methods in the same class create a
monitor.
wait, notify and notifyAll can only be called
upon a locked object.
Calling wait unlocks the object and adds the
thread to the objects wait set.
8
A Binary Semaphore
public class LockableObject private int
semaValue public LockableObject()
semaValue 0 public synchronized
void lockedWait() semaValue-- if
(semaValue lt 0) try
wait() catch (InterruptedException
e) public synchronized void
lockedSignal() semaValue if
(semaValue lt 0) notify()
9
Using LocableObject
public class MyThread extends Thread
public LockableObject semaphore new
LockableObject() public void run()
semaphore.lockedWait() for (int j1
jlt5 j) System.out.println(Thre
ad.currentThread()" loop counter"j)
runAwhile() public void
runAwhile() ...
public class Driver public static void
main(String args) MyThread threadA,
threadB threadA new MyThread()
threadA.start() threadB
new MyThread() threadB.start()
System.out.println("The Driver has started other
threads.") threadA.semaphore.lockedSignal()
threadB.semaphore.lockedSignal()
try threadA.join()
threadB.join() catch (InterruptedExceptio
n e) System.out.println(All threads are
finished!)
10
Yet Another Producer-Consumer
Producer thread
Consumer thread
monitorObj.depositData(data)
monitorObj.removeData(data)
public class Monitor private final int
numberOfBuffers 100 private int
buffersInUse 0 public Monitor() //
constructor method public
synchronized void depositData( int data )
while (buffersInUse numberOfBuffers)
try wait() catch
(InterruptedException e)
//placeInNextAvailableBuffer(Data)
buffersInUse notifyAll()
public synchronized int removeData() while
(buffersInUse 0) try wait()
catch (InterruptedException e)
//remove data from oldest buffer
buffersInUse-- notifyAll() return
dataJustRemoved
11
Additional Thread Operations
isAlive() - from Thread
Returns true unless the thread is dead.
obj.join() - from Thread
Causes the executing thread to suspend awaiting
the obj thread to die.
interrupt() - from Thread
If the thread is blocked via wait or join, then
InterruptException is thrown. If the thread is
blocked for I/O, then ClosedByInterruptException
is thrown.
setPriority(int p) - from Thread
Assigns a priority to a thread. Higher numbers
mean higher priority to execute.
setDaemon(boolean on) - from Thread
Sets a thread as a daemon or not. Daemons can
continue to run in the background when a program
terminates.
suspend(), resume(), stop() - from Thread
All are deprecated!
Write a Comment
User Comments (0)
About PowerShow.com