Title: Threads
1Threads
2Multitasking
- Windows 95, Unix and many other operating systems
allow multitasking. printing while doing word
processing,etc - The operating system gives the user the
impression of concurrent operation. - The user works in the foreground, in idle moments
a background task is executed.
3Types of Multitasking
- Co-operative multitasking
- also known as non-pre-emptive
- Windows 3.1
- program is responsible for giving up processor
- Pre-emptive multitasking
- Windows 95 (32-bit), NT, Unix
- Operating system shares resources
- More difficult to implement but better results
4Processes
- Multitasking is achieved by way of processes.
- Processes are active programs with their own
memory space. - Operating systems prevent processes from
interfering with each other. - Processes can communicate via an inter-process
communication mechanism.
5Process vs Thread
- A process is an executing program.
- Allocated memory by the operating system.
- A thread is an execution in the address space of
a process the program counter register points to
the next instruction to be executed. - A process can have more than one thread.
- All the threads in a process have their own
program counter and their own stack for local
(also called automatic) variables and return
addresses of invoked procedures.
6Multithreading
- Concurrent strands (threads) of activity within a
program. - Threads run as if each had its own CPU, registers
and memory. - BUT threads share memory with each other.
- Less secure than a process but less overhead.
- The JDK comes with a Thread class to enable
multithreading.
7Concurrent Program Execution
8Concurrent Program Execution
- In Java, a thread in the run-time interpreter
calls the main() method of the class on the java
command line. - Each object created can have one or more threads,
all sharing access to the data fields of the
object.
9Thread class
- All classes inheriting from Thread must override
the method run(). - This method should not be called directly from
an application or applet. It is invoked by the
JVM when the thread is executed. - The start() method is called to begin execution
of a thread. The method requests the JVM to
schedule the thread.
10Using Threads
- Java provides two ways of associating a Thread
object with a run method - Declare a subclass of Thread that defines a run()
method. When such a class is instantiated and the
object's start() method is called, the thread
invokes this run() method. - Pass a reference to an object that implements the
Runnable interface to a Thread constructor. When
the start() method of such a Thread object is
called, the thread invokes the run() method of
the Runnable object.
11Thread class methods
- void run()
- Must be overridden, not called directly
- void start()
- Called to begin execution of a thread.
- static native void sleep (long m)
- Makes the currently running thread pause for the
number of milliseconds specified.
12Extending the Thread class ex. 1
- /
- This is a thread class that prints the numbers
from 1 to 10. It - is run by the main program, which also prints
numbers from 1 to 10 - /
- public class PrintNums extends Thread
-
- public void run()
-
- for ( int i 0 i lt10 i)
- System.out.println( "\tPrintNums
Thread " i) -
-
For a thread to do anything meaningful, it must
override the Thread class run() method
13Extending the Thread class ex. 1
- / Main program which is the main thread. This
prints numbers from one to 0 and controls the
thread PrintNums, which also prints numbers
from 1 to 10. - /
- public class IntroThread
-
- public static void main ( String args )
-
- // Create a new thread
- PrintNums t1 new PrintNums()
- // start the run method of the thread
- t1.start()
- for ( int i1 ilt10 i )
System.out.println ("Main thread " i) -
- // end IntroThread
PrintNums extends Thread.
14Implementing the Runnable interface Ex. 2
- public class RunEx1 extends Object implements
Runnable -
- // User must implement the run() in
Runnable - public void run()
-
- for ( int i1 ilt10 i )
- System.out.println("Thread 1 " i)
-
- // end RunEx1
The Runnable interface contains only one method
run()
15Implementing the Runnable interface Ex. 2
- // This is a main thread that prints the numbers
from 1 to 10 - public class Run1
-
- public static void main ( String args )
- RunEx1 a1 new RunEx1() //
create a runnable object - Thread t1 new Thread (a1) // t1
runs a1's run() - // or alternatively Thread t1 new
Thread ( a1, "threadname") - t1.start()
- for ( int i1 ilt 10 i)
- System.out.println ("gt Main
thread " i) -
-
16Should I use Runnable or extend Thread?
- Rule of Thumb
- If your class must subclass some other class (the
most common example being Applet), you should
use Runnable
17Synchronizing threads
- Threads carry out operations at unpredictable
times. - Timing depends on the changing operating
environment. - If two threads are running, the order of their
operations is unpredictable. - If two threads operate on the same data then
output is unpredictable.
18Thread States
- New
- runnable
- blocked
- dead
19Thread States
20New threads
- A just created thread
- Not yet executed.
- Requires memory allocation etc before it can
execute. - Invoking the start() method for this thread will
allocate memory to the thread and make it
runnable.
21Runnable threads
- Runnable means may be executed.
- Only one runnable thread may be executed at a
time. - On execution code is running.
- JVM selects which of the runnable threads may
execute. - Difference in operating system implementations.
22Blocked threads
- A thread is blocked when
- the sleep() method is invoked
- it calls wait()
- it has to wait for input/output
- the suspend() method is invoked
- When a thread moves into the blocked state, the
JVM can select another one to run.
23Unblocking
- A thread becomes unblocked when
- its sleep period expires
- It is notified
- The I/O operation it is waiting on completes
- Some code calls the resume() method for it
- The unblocking action must match the action that
called the block.
24Dead Threads
- A thread ceases to exists when
- its run() method exits
- its stop() method is called
- A thread instantiation that has died cannot
become runnable again
Stop() is now deprecated
25Thread class constructors constants
- public class java.lang.Thread extends
java.lang.Object -
implements java.lang.Runnable - // Constants
- public final static int MAX_PRIORITY
- public final static int MIN_PRIORITY
- public final static int NORM_PRIORITY
- // Constructors
- public Thread()
- public Thread(Runnable target)
- public Thread(Runnable target, String name)
- public Thread(String name)
- public Thread(ThreadGroup group, Runnable
target) - public Thread(ThreadGroup group, Runnable
target, String name) - public Thread(ThreadGroup group, String name)
26Thread class methods
- // Class Methods
- public static int activeCount()
- public static native Thread currentThread()
- public static void dumpStack()
- public static int enumerate (Thread
tarray) - public static boolean interrupted()
- public static native void sleep(long millis)
- public static void sleep(long millis, int
nanos) - public static native void yield()
-
27Thread class instance methods
- // Instance Methods
- public void checkAccess()
- public native int countStackFrames()
- public void destroy()
- public final String getName()
- public final int getPriority()
- public final ThreadGroup getThreadGroup()
- public void interrupt()
- public final native boolean isAlive()
- public final boolean isDaemon()
- public boolean isInterrupted()
- public final void join()
- public final synchronized void join(long
millis) - public final synchronized void join(long
millis, int nanos)
28Thread class instance methods cont.
- // Instance Methods
- public final void resume()
- public void run()
- public final void setDaemon(boolean on)
- public final void setName(String name)
- public final void setPriority(int
newPriority) - public synchronized native void start()
- public final void stop()
- public final synchronized void stop(Throwable
o) - public final void suspend()
- public String toString()
-
Those in pink have been deprecated should no
longer be used
29Time to wake up.
Have a Nice Weekend!!