Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Multithreaded Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Multithreaded Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Multithreaded Programming

• A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of
execution.
• Thus, multithreading is a specialized form of multitasking.
• There are 2 distinct types of multitasking: process-based & thread-based.
• A process is a program that is executing. Thus, 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. This means that a single program can perform two or more tasks
simultaneously.
• Multitasking threads require less overhead than multitasking processes.
The Java Thread Model
• Java uses threads to reduce inefficiency by preventing the waste of CPU
cycles.
• One thread can pause without stopping other parts of your program.
• For ex: the idle time created when a thread reads data from a network or
waits for user input can be utilized elsewhere. When a thread blocks in a
Java program, only the single thread that is blocked pauses. All other
threads continue to run.
Threads exist in several states.

• A thread can be running.

• It can be ready to run as soon as it gets CPU time.

• A running thread can be suspended, which temporarily suspends its activity.

• A suspended thread can then be resumed, allowing it to pick up where it left off.

• A thread can be blocked when waiting for a resource.

• At any time, a thread can be terminated, which halts its execution immediately.

• Once terminated, a thread cannot be resumed.


Thread Priorities
• Java assigns to each thread a priority that determines how that thread should be treated
with respect to the others.
• Thread priorities are integers that specify the relative priority of one thread to another.
• A thread’s priority is used to decide when to switch from one running thread to the next.
This is called a context switch.
• A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or
blocking on pending I/O. In this scenario, all other threads are examined, and the highest-
priority thread that is ready to run is given the CPU.
• A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread
that does not yield the processor is simply preempted—no matter what it is doing—by a
higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does.
This is called preemptive multitasking.
Synchronization
• you must prevent one thread from writing data while another thread is in
the middle of reading it.
• For this purpose, Java implements an elegant twist on an age-old model
of inter-process synchronization: the monitor.
• The monitor is a control mechanism.
• Once a thread enters a monitor, all other threads must wait until that
thread exits the monitor. In this way, a monitor can be used to protect a
shared asset from being manipulated by more than one thread at a time.
• Once a thread is inside a synchronized method, no other thread can call
any other synchronized method on the same object.
The Thread Class and the Runnable Interface
• Java’s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable.
• 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.
The Main Thread
• When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of your program, because it is the one that is
executed when your program begins.
• The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• it must be the last thread to finish execution because it performs various
shutdown actions.
• Although the main thread is created automatically when your program is started, it
can be controlled through a Thread object.
• To do so, you must obtain a reference to it by calling the method currentThread( ).
static Thread currentThread( )
Controlling the main Thread.
catch (InterruptedException e)
class CurrentThreadDemo { {
public static void main(String args[]) { System.out.println("Main thread
interrupted"); }
Thread t = Thread.currentThread();
}
System.out.println("Current thread: " + t); }
// change the name of the thread
Current thread: Thread[main,5,main]
t.setName("My Thread"); After name change: Thread[My Thread,5,main]

System.out.println("After name change:"+t); 5


4
try { 3
for(int n = 5; n > 0; n--) { 2
System.out.println(n); 1

Thread.sleep(1000); } A thread group is a data structure that controls the


} state of a collection of threads as a whole
Creating a Thread
you create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.
Implementing Runnable:
• The easiest way to create a thread is to create a class that implements the Runnable interface.
Runnable abstracts a unit of executable code.
• To implement Runnable, a class need only implement a single method called run( ),
public void run( )
• Inside run( ), you will define the code that constitutes the new thread.
• It is important to understand that run( ) can call other methods, use other classes, and declare
variables, just like the main thread can.
• After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ).
Implementing Runnable
class ThreadDemo {
class NewThread implements Runnable { public static void main(String args[]) {
Thread t; new NewThread(); // create a new thread
NewThread() { // Create a new, second thread try {
t = new Thread(this, "Demo Thread"); for(int i = 5; i > 0; i--) {
System.out.println("Child thread: " + t);
System.out.println("Main Thread: " + i);
t.start(); // Start the thread }
Thread.sleep(1000); }
// This is the entry point for the second thread.
public void run() { }
try { catch (InterruptedException e) {
for(int i = 5; i > 0; i--) { System.out.println("Main thread interrupted."); }
System.out.println("Child Thread: " + i); System.out.println("Main thread exiting."); }
Thread.sleep(500); } }
}
Child thread: Thread[Demo Thread,5,main]
catch (InterruptedException e) { Main Thread: 5 Main Thread: 3
System.out.println("Child interrupted."); } Child Thread: 5 Child Thread: 1
Child Thread: 4 Exiting child thread.
System.out.println("Exiting child thread."); } Main Thread: 4 Main Thread: 2
Child Thread: 3 Main Thread: 1
} Child Thread: 2 Main thread exiting.
Extending Thread Class
class ThreadDemo {
class NewThread extends Thread { public static void main(String args[]) {
NewThread() { // Create a new, second thread new NewThread(); // create a new thread

super("Demo Thread"); try {


for(int i = 5; i > 0; i--) {
System.out.println("Child thread: " + this);
System.out.println("Main Thread: " + i);
start(); } // Start the thread
Thread.sleep(1000); }
// This is the entry point for the second thread.
public void run() { }
try { catch (InterruptedException e) {
for(int i = 5; i > 0; i--) { System.out.println("Main thread interrupted."); }
System.out.println("Child Thread: " + i); System.out.println("Main thread exiting."); }
Thread.sleep(500); } }
}
Child thread: Thread[Demo Thread,5,main]
catch (InterruptedException e) { Main Thread: 5 Main Thread: 3
Child Thread: 5 Child Thread: 1
System.out.println("Child interrupted."); } Child Thread: 4 Exiting child thread.
System.out.println("Exiting child thread."); } Main Thread: 4 Main Thread: 2
Child Thread: 3 Main Thread: 1
} Child Thread: 2 Main thread exiting.
catch (InterruptedException e) {
class NewThread implements Runnable { System.out.println(name + "Int errupted"); }
String name; // name of thread System.out.println(name + " exiting.");
Thread t; }
NewThread(String threadname) { }
name = threadname; class MultiThreadDemo {
t = new Thread(this, name); public static void main(String args[]) {
System.out.println("New thread: " + t); new NewThread("One"); // start threads
t.start(); // Start the thread } new NewThread("Two");
// This is the entry point for thread. new NewThread("Three");
public void run() { try { // wait for other threads to end
try { Thread.sleep(10000); }
for(int i = 5; i > 0; i--) { catch (InterruptedException e) {
System.out.println(name + ": " + i); System.out.println("Main thread Interrupted"); }
Thread.sleep(1000); } System.out.println("Main thread exiting."); }
} }

You might also like