Programming in Java
Topic: Multi-threading
Introduction
• Concurrent Execution of multiple tasks is called Multitasking.
Multitasking
Multi-processing Multi-threading
(Process-based) (Thread-based)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
• Multithreading is a specialized form of multitasking.
• A multithreaded program contains two or more parts (threads)
that can run concurrently.
• Each thread defines a separate path of execution.
• Java provides built-in support for multithreaded programming.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Process and Threads
• In concurrent programming, there are two basic units of execution:
processes and threads.
• Process: is an executable program loaded in memory
» has its own Variables & data structures (in memory)
» Communicate via operating system, files, network
» May contain multiple threads
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Threads
• A thread is an independent module of an application that can be
concurrently executed with other threads.
• Also known as “lightweight process”.
• Threads exist within a process — every process has at least one.
• Multiple threads in process execute same program.
• Threads share the process's resources, including memory and
open files.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• A thread cannot exist on its own; it must be a part of a process.
• A process remains running until all of the non-daemon threads
are done executing.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Life Cycle of a Thread
• New: The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
• Runnable: The thread is in runnable state after invocation of
start() method, but the thread scheduler has not selected it to
be the running thread.
• Running: The thread is in running state if the thread
scheduler has selected it.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• Waiting/Blocked: This is the state when the thread is still
alive, but is currently not eligible to run.
• Terminated: A thread is in terminated or dead state when its
run() method exits.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Multithreading in Java
• In order to achieve multithreading in java application,
java.lang.Runnable interface is provided.
• java.lang.Thread class is provided as part of core java library
which provides methods that are used to:
– start and suspend a thread
– obtain the state of a thread
– change the state of a thread
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Runnable Interface
• java.lang.Runnable interface provides the mechanism to
demarcate independent modules.
• Runnable interface contains a single method run().
public interface Runnable {
public void run();
}
• run() is executed by JVM as a thread.
• main() is also executed as a thread by JVM and is called main
thread.
• Main thread acts as the parent of all user threads.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Thread Class
• Thread class provides methods to start a thread, suspend a
thread and obtain the state of a thread.
public class Thread {
public Thread()
public Thread(String s)
public Thread(Runnable R); // Thread ⇒ R.run()
public Thread(Runnable R, String name);
public void start(); // begin thread execution
...
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Thread class
• currentThread(): used to obtain the reference of thread
object for the current thread.
public static Thread currentThread()
• getName(): returns the name of the thread.
public String getName()
• setName(): used to change the name of a thread.
public void setName(String Name)
• getPriority(): used to obtain the priority of thread.
public int getPriority()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Thread class
• setPriority(): used to obtain the priority of thread.
public void setPriority(int p)
• start(): used to start the execution of a thread.
public void start()
• sleep(): is used to suspend the current thread for the specified time.
public static void sleep(long milliseconds) throws InterruptedException
• isAlive(): used to find out whether a thread is completed or not .
public boolean isAlive()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating Threads in Java
• A user thread is represented by run().
• There are two ways of defining a thread:
– By extending Thread class
– By implementing Runnable interface
Runnable Runnable
Thread
MyThread MyThread
• The first case is not recommended because our class may already
have a super class, so we can not extend another class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Implementing Runnable
• We can construct a thread on any object that implements Runnable.
• To implement Runnable, a class need only implement run( ).
• Inside run( ), we 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 can.
• The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within our program.
• This thread will end when run( ) returns.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class MyThread implements Runnable
{
Thread t;
MyThread()
{
t = new Thread(this, "My Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run()
{
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
} Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class ThreadDemo1
{
public static void main(String args[])
{
new MyThread();
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

L22 multi-threading-introduction

  • 1.
  • 2.
    Introduction • Concurrent Executionof multiple tasks is called Multitasking. Multitasking Multi-processing Multi-threading (Process-based) (Thread-based) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3.
    Introduction • Multithreading isa specialized form of multitasking. • A multithreaded program contains two or more parts (threads) that can run concurrently. • Each thread defines a separate path of execution. • Java provides built-in support for multithreaded programming. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4.
    Process and Threads •In concurrent programming, there are two basic units of execution: processes and threads. • Process: is an executable program loaded in memory » has its own Variables & data structures (in memory) » Communicate via operating system, files, network » May contain multiple threads Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5.
    Threads • A threadis an independent module of an application that can be concurrently executed with other threads. • Also known as “lightweight process”. • Threads exist within a process — every process has at least one. • Multiple threads in process execute same program. • Threads share the process's resources, including memory and open files. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6.
    • A threadcannot exist on its own; it must be a part of a process. • A process remains running until all of the non-daemon threads are done executing. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7.
    Life Cycle ofa Thread • New: The thread is in new state if you create an instance of Thread class but before the invocation of start() method. • Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. • Running: The thread is in running state if the thread scheduler has selected it. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8.
    • Waiting/Blocked: Thisis the state when the thread is still alive, but is currently not eligible to run. • Terminated: A thread is in terminated or dead state when its run() method exits. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9.
    Ravi Kant Sahu,Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10.
    Multithreading in Java •In order to achieve multithreading in java application, java.lang.Runnable interface is provided. • java.lang.Thread class is provided as part of core java library which provides methods that are used to: – start and suspend a thread – obtain the state of a thread – change the state of a thread Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11.
    Runnable Interface • java.lang.Runnableinterface provides the mechanism to demarcate independent modules. • Runnable interface contains a single method run(). public interface Runnable { public void run(); } • run() is executed by JVM as a thread. • main() is also executed as a thread by JVM and is called main thread. • Main thread acts as the parent of all user threads. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12.
    Thread Class • Threadclass provides methods to start a thread, suspend a thread and obtain the state of a thread. public class Thread { public Thread() public Thread(String s) public Thread(Runnable R); // Thread ⇒ R.run() public Thread(Runnable R, String name); public void start(); // begin thread execution ... } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13.
    Methods of Threadclass • currentThread(): used to obtain the reference of thread object for the current thread. public static Thread currentThread() • getName(): returns the name of the thread. public String getName() • setName(): used to change the name of a thread. public void setName(String Name) • getPriority(): used to obtain the priority of thread. public int getPriority() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14.
    Methods of Threadclass • setPriority(): used to obtain the priority of thread. public void setPriority(int p) • start(): used to start the execution of a thread. public void start() • sleep(): is used to suspend the current thread for the specified time. public static void sleep(long milliseconds) throws InterruptedException • isAlive(): used to find out whether a thread is completed or not . public boolean isAlive() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15.
    Creating Threads inJava • A user thread is represented by run(). • There are two ways of defining a thread: – By extending Thread class – By implementing Runnable interface Runnable Runnable Thread MyThread MyThread • The first case is not recommended because our class may already have a super class, so we can not extend another class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16.
    Implementing Runnable • Wecan construct a thread on any object that implements Runnable. • To implement Runnable, a class need only implement run( ). • Inside run( ), we 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 can. • The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within our program. • This thread will end when run( ) returns. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17.
    class MyThread implementsRunnable { Thread t; MyThread() { t = new Thread(this, "My Thread"); System.out.println("Child thread: " + t); t.start(); } public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18.
    class ThreadDemo1 { public staticvoid main(String args[]) { new MyThread(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)