Lect01: Multithreaded Programming: Writing Concurrently Running Threads

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

Lect01: Multithreaded

Programming
Writing concurrently running threads
Multithreaded Programming
• Java supports one program to have many
processes running in memory at the same
time.
• These concurrently running processes are
called threads and each thread has its own
path of execution.
• Multithreaded programming is an approach
Java is using to implement multitasking
What you should understand
• Understand multithreading fundamentals
• Know the Thread class and the Runnable interface
• Create a thread
• Create multiple threads
• Determine when a thread ends
• Use thread priorities
• Understand thread synchronization
• Use synchronized methods
• Use synchronized blocks
• Communicate between threads
• Suspend, resume, and stop threads
Multithreading Fundamentals
• Two distinct types of multitasking:
– process-based and
– thread-based.
• A process is a program that is executing. A process-based
multitasking is the feature that allows your computer to run
two or more programs concurrently. In process-based
multitasking, a program is the smallest unit of code that can
be dispatched by the scheduler.
• In a thread-based multitasking environment, the thread is
the smallest unit of dispatchable code. A single program
can perform two or more tasks at once. Eg a text editor can
be formatting text at the same time that it is printing, as
long as these two actions are being performed by two
separate threads.
Thread States
• A thread can be in one of several states.
– It can be running.
– It can be ready to run as soon as it gets CPU
time.
– A running thread can be suspended, which is a
temporary halt to its execution.
– It can later be resumed.
– A thread can be blocked when waiting for a
resource.
– A thread can be terminated, in which case its
execution ends and cannot be resumed.
The Thread Class and Runnable Interface

• Thread encapsulates a thread of execution. To create


a new thread, your program will either extend
Thread or implement the Runnable interface.
• The Thread class defines several methods that help
manage threads
• All processes have at least one thread of execution,
which is usually called the main thread, because it is
the one that is executed when your program begins.
From the main thread, you can create other threads.
Thread Class

Method Task
final String getName( ) Obtains a thread’s name
final int getPriority( ) Obtains a thread’s priority.
final boolean isAlive( ) Determines whether a thread is
still running
final void join( ) Waits for a thread to terminate
void run( ) Entry point for the thread
static void sleep(long Suspends a thread for a specified
milliseconds) period of milliseconds
void start( ) Starts a thread by calling its run( )
method
Creating a Thread
• You create a thread by instantiating an object of type Thread. The
Thread class encapsulates an object that is runnable. Java defines
two ways in which you can create a runnable object:
– You can implement the Runnable interface.
– You can extend the Thread class.
• Both approaches use the Thread class to instantiate, access, and
control the thread.
• The only difference is how a thread-enabled class is created.
• The Runnable interface abstracts a unit of executable code.
• You can construct a thread on any object that implements the
Runnable interface. Runnable defines only one method called
run( ), which is declared like this:
public void run( )
• Inside run( ), you will define the code that constitutes the new
thread.
• run( ) can call other methods, use other classes, and declare
variables just like the main thread.
• The only difference is that run( ) establishes the entry point for
another, concurrent thread of execution within your program. This
thread will end when run( ) returns.
• After you have created a class that implements Runnable, you will
instantiate an object of type Thread on an object of that class.
• Thread defines several constructors, eg:
Thread(Runnable threadOb)
• threadOb is an instance of a class that implements the Runnable
interface
• Start the thread by calling its start( ) method, which is declared
within Thread.
• start( ) executes a call to run( ).
Stages
• Implement the runnable class.
– write code for run() method
– The run() method is the starting point of execution
of a concurrent thread
– The execution logic of your thread will be
implemented in run() method
• In main() method (or another run() method)
– Create object (instantiate) of your new thread, ie
the object of class (above) that implements
runnable
– Create the thread by passing your new object
– Call the start method of this thread
Example skeleton
• Implement the runnable class
class MyThread implements Runnable{
//some code
public void run() { //starting point of execution
//some code for execution logic
}
}
• Write the main program  main() method
public class UseThreads {
public static void main(String args[]) {
//Some code
//construct a MyThread object.
MyThread mt = new MyThread("Child #1");
// Next, construct a thread from that object.
Thread newThrd = new Thread(mt);
// Finally, start execution of the thread.
newThrd.start();
//Some code
}
}
class MyThread implements Runnable{
int count; String thrdName;
MyThread(String name) {
count = 0; thrdName = name;
}
public void run() {// Entry point of thread.
System.out.println(thrdName + " starting.");
try {
do {
Thread.sleep(500);
System.out.println("In " + thrdName +", count is " + count);
count++;
} while(count < 10);
}catch(InterruptedException exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
}
public class UseThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");
// First, construct a MyThread object.
MyThread mt = new MyThread("Child #1");
// Next, construct a thread from that object.
Thread newThrd = new Thread(mt);
// Finally, start execution of the thread.
newThrd.start();
do {
System.out.print("*");
try {
Thread.sleep(100);
}catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
} while (mt.count != 10);
System.out.println("Main thread ending.");
}}
Output
Main thread starting.
*Child #1 starting.
****In Child #1, count is 0
*****In Child #1, count is 1
*****In Child #1, count is 2
****In Child #1, count is 3
*****In Child #1, count is 4
*****In Child #1, count is 5
****In Child #1, count is 6
*****In Child #1, count is 7
****In Child #1, count is 8
*****In Child #1, count is 9
Child #1 terminating.
Main thread ending.
• The sleep( ) method causes the thread from which it is called
to suspend execution for the specified period of milliseconds.
• calls to sleep() must be wrapped in a try/catch block
• Steps
1. main() calls mythread, and continues running (by
printing of ‘*’)
2. main() encounters sleep, thus goes to suspend state
3. main() waits 100ms
4. mythread prints ‘Child #1 starting’ and goes to suspend
mode for 500ms
5. The suspend mode of main() expires, it wakes and print
‘*’, goes again to sleep mode, wake up, goes to sleep
mode, wake up [at interval of 100ms]
6. After the 500ms finishes, mythread wakes up, print the
value of count, sleep again waiting for 500ms, etc
Creating Thread by Extending Thread Class

• When a class extends a thread class,


– It must override the run() method since this
equivalent to main()
– It must call start() method to make the thread
starts
– you don’t need to declare or create the thread
object as the class itself is the thread, and it can
call itself
– Call the thread’s constructor by using super
class MyThread extends Thread {
int count;
MyThread(String name) { // Construct a new thread.
super(name); // name thread
count = 0;
start(); // start the thread
}
public void run() { // Begin execution of new thread.
System.out.println(getName() + " starting.");
try {
do {
Thread.sleep(500);
System.out.println("In " + getName() + ", count is " + count);
count++;
} while(count < 10);
} catch(InterruptedException exc) {
System.out.println(getName() + " interrupted.");
}
System.out.println(getName() + " terminating.");
}
}
class ExtendThread {
public static void main(String args[]) {
System.out.println("Main thread starting.");
MyThread mt = new MyThread("Child #1");
do {
System.out.print(".");
try {
Thread.sleep(100);
}catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
} while (mt.count != 10);
System.out.println("Main thread ending.");
}
}
Creating Multiple Threads
• It possible to create more than one thread
• The approach is the same
• What is different is during thread creation in statement like this:
MyThread mt = new MyThread("Child #1");
• You can add more threads by writing:
MyThread mt1 = new MyThread("Child #1");
MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");
MyThread mt4 = new MyThread("Child #4");
• Four threads have been created
Determining When a Thread Ends
• Thread provides two means by which you can
determine if a thread has ended.
– You can call isAlive( ) on the thread.
– You can call join( )
• The general forms are:
– final boolean isAlive( )
– final void join( ) throws InterruptedException

You might also like