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

Object Oriented Programming

19CSE (2nd Semester)


Chapter#10: Multithreading in Java

1
Introduction to Multithreading
What is a Thread?
 A thread is actually a lightweight process that executes some task
 A piece of code that run in concurrent with other threads.
 Threads are being extensively used to express concurrency on both
single and multiprocessors machines.
What is a thread in java?
 Unlike many other computer languages, Java provides built-in support
for multithreaded programming.
 Java provides Thread class and an application can create multiple
threads executing concurrently.
 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 the execution.
 Thus, multithreading is a specialized form of multitasking.
Introduction to Multithreading
 Multiprocessing and multithreading, both are used to achieve
multitasking.
 However, we use multithreading than multiprocessing because
threads use a shared memory area.
 They don't allocate separate memory area so it saves memory, and
context-switching between the threads takes less time than
process.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
Introduction to Multithreading
 There are two types of thread
 user thread
 daemon thread 
 Daemon threads are “background” threads, that provide services to other
threads, e.g., the garbage collection thread
 daemon threads are used when we want to clean the application and are used in
the background.
 When an application first begins, user thread is created.
 we can create many user threads and daemon threads.
Why we need threads?
 To enhance parallel processing
 To increase response to the user
 To utilize the idle time of the CPU
 Prioritize your work depending on priority
Example: Consider a simple web server
 The web server listens for request and serves it. If the web server was not
multithreaded, the requests processing would be in a queue, thus increasing the
response time and also might hang the server if there was a bad request.
Introduction to Multithreading
What is Multitasking
 Multitasking is a process of executing multiple tasks simultaneously.
 We use multitasking to utilize the CPU.
 Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing)
2) Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
 Each process has an address in memory. In other words, each process allocates
a separate memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.
Life cycle of a Thread (Thread States)
 A thread can be in one of the five states.
 According to sun, there is only 4 states in thread life cycle in java
new, runnable, non-runnable and terminated. There is no running
state.
 But for better understanding the threads, we are explaining it in
the 5 states.
 The life cycle of the thread in java is controlled by JVM. The java
thread states are as follows:
1) New
2) Runnable
3) Running
4) Non-Runnable (Blocked)
5) Terminated
Life cycle of a Thread (Thread States)
Life cycle of a Thread (Thread States)
1) New
 The thread is in new state if you create an instance of Thread class
but before the invocation of start() method.
2) 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.
3) Running
 The thread is in running state if the thread scheduler has selected
it.
4) Non-Runnable (Blocked)
 This is the state when the thread is still alive, but is currently not
eligible to run.
5) Terminated
 A thread is in terminated or dead state when its run() method exits.
Thread Class
 Thread class provide constructors and methods to create and perform
operations on a Thread.
 Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
 Thus, multithreading is a specialized form of multitasking.
Commonly used methods of Thread class:
1) public void run(): is used to perform action for a thread.
2) public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
3) public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number
of milliseconds.
Thread Class
Commonly used methods of Thread class:
4) public void join(): waits for a thread to die.
5) public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6) public int getPriority(): returns the priority of the thread.
7) public int setPriority(int priority): changes the priority of the thread.
8) public String getName(): returns the name of the thread.
9) public void setName(String name): changes the name of the thread.
10) public Thread currentThread(): returns the reference of currently
executing thread.
11) public int getId(): returns the id of the thread.
12) public Thread.State getState(): returns the state of the thread.
13) public boolean isAlive(): tests if the thread is alive.
14) public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
Thread Class
Commonly used methods of Thread class:
15) public void suspend(): is used to suspend the thread(depricated).
16) public void resume(): is used to resume the suspended
thread(depricated).
17) public void stop(): is used to stop the thread(depricated).
18) public boolean isDaemon(): tests if the thread is a daemon thread.
19) public void setDaemon(boolean b): marks the thread as daemon or
user thread.
20) public void interrupt(): interrupts the thread.
21) public boolean isInterrupted(): tests if the thread has been
interrupted.
22) public static boolean interrupted(): tests if the current thread has
been interrupted.
How to create thread in Java?
There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.
By Extending Thread Class
 The first way to create a thread is to create a new class that extends Thread,
then override the run() method and then to create an instance of that class.
 The run() method is what is executed by the thread after you call start().
Here is an example of creating a Java Thread subclass:
public class MyClass extends Thread
{
public void run()
{
System.out.println("MyClass running");
}
}
 To create and start the above thread:
MyClass t1 = new MyClass ();
T1.start();
 When the run() method executes it will print out the text " MyClass running ".
 So far, we have been using only two threads: the main thread and one child
thread. However, our program can affect as many threads as it needs.
An example(Extending
class MyThread extends Thread
thread class)
{
// the thread
public void run()
{
System.out.println(" this thread is running ... ");
}
} // end class MyThread

class ThreadEx1
{
// a program that utilizes the thread
public static void main(String [] args )
{
MyThread t = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
t.start();
} // end main()
} // end class ThreadEx1 14
By implementing Runnable interface.
 The easiest way to create a thread is to create a class that implements the Runnable
interface.
 To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:
public void run( )
 Inside run( ), we will define the code that constitutes the new thread.
Here is an Example:
public class MyClass implements Runnable
{
public void run()
{
System.out.println("MyClass running");
}
}
 To execute the run() method by a thread, pass an instance of MyClass to a Thread in its
constructor. Here is how that is done:
Thread t1 = new Thread(new MyClass ());
t1.start();
 When the thread is started it will call the run() method of the MyClass instance instead
of executing its own run() method. The above example would print out the text
"MyClass running ".
An example: Implementing runnable interface
class MyThread implements Runnable
{
public void run()
{

System.out.println(" this thread is running ... ");


}
} // end class MyThread

class ThreadEx2
{
public static void main(String [] args )
{
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// I can call start(), and this will call run().
t.start();
} // end main()
} // end class ThreadEx2
16
Program#01
Program that creates three threads
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}

System.out.println("Exit from A");


}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}

System.out.println("Exit from B");


}
}
17
Program#01
Program that creates three threads
class C extends Thread
{
public void run()
{

for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}

System.out.println("Exit from C");


}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();

}
}
18
Run 1
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B

19
Run2
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A
20
1 // ThreadTester.java Outline
2 // Show multiple threads printing at different intervals.
3
4 public class ThreadTester {
5
ThreadTester.java
6 // create and start threads
7 public static void main( String args[] ) Lines 4-28
8 { Class
9 PrintThread thread1, thread2, thread3, thread4;
10 ThreadTester
11 // create four PrintThread objects creates four
12 thread1 = new PrintThread( "thread1" ); PrintThreads and
13 thread2 = new PrintThread( "thread2" );
14 thread3 = new PrintThread( "thread3" ); calls their start
15 thread4 = new PrintThread( "thread4" ); methods
16
17 System.err.println( "\nStarting threads" );
18
19 // start executing PrintThreads
20 thread1.start();
21 thread2.start();
22 thread3.start();
23 thread4.start();
24
25 System.err.println( "Threads started\n" );
26 }
27
28 } // end class ThreadTester
29

 2002 Prentice Hall, Inc.


All rights reserved.
30 // Each object of this class picks a random sleep interval.
31 // When a PrintThread executes, it prints its name, sleeps,
Outline
32 // prints its name again and terminates.
33 class PrintThread extends Thread {
34 private int sleepTime; ThreadTester.java
PrintThread
35
36 // PrintThread constructor assigns name to thread inherits from
Lines 33-71
37 // by calling superclass Thread constructor Thread so each
38 public PrintThread( String name )
39 {
object of the class can
Lines 38-48
40 super( name ); execute in parallel
41
Lines 51-69
42 // sleep between 0 and 5 seconds
43 sleepTime = (int) ( Math.random() * 5000 );
44 Constructor initializes
45 // display name and sleepTime sleepTime to be 0
46 System.err.println( to 4.999 seconds and
47 "Name: " + getName() + "; sleep: " + sleepTime );
48 } outputs name and
49 value of
50 // control thread's execution sleepTime
51 public void run()
52 {
53 // put thread to sleep for a random interval
54 try {
55 System.err.println( getName() + " going to sleep" );
Thread run method
56 prints a String
57 // put thread to sleep saying the thread is
58 Thread.sleep( sleepTime );
59 }
going to sleep and
thread sleeps

 2002 Prentice Hall, Inc.


All rights reserved.
60 Outline
61 // if thread interrupted during sleep, catch exception
62 // and display error message
63 catch ( InterruptedException interruptedException ) {
64 System.err.println( interruptedException.toString() );
ThreadTester.java
65 }
66 Line 68
67 // print thread name Thread prints name
68 System.err.println( getName() + " done sleeping" );
69 } when done sleeping
70
71 } // end class PrintThread

 2002 Prentice Hall, Inc.


All rights reserved.
Name: thread1; sleep: 3593 Outline
Name: thread2; sleep: 2653
Name: thread3; sleep: 4465
Name: thread4; sleep: 1318
  Program Output
Starting threads
Threads started
 
thread1 going to sleep
thread2 going to sleep
thread3 going to sleep
thread4 going to sleep
thread4 done sleeping
thread2 done sleeping
thread1 done sleeping
thread3 done sleeping

Name: thread1; sleep: 2753


Name: thread2; sleep: 3199
Name: thread3; sleep: 2797
Name: thread4; sleep: 4639
 
Starting threads
Threads started
 
thread1 going to sleep
thread2 going to sleep
thread3 going to sleep
thread4 going to sleep
thread1 done sleeping
thread3 done sleeping
thread2 done sleeping
thread4 done sleeping
 2002 Prentice Hall, Inc.
All rights reserved.
Algorithm example
• Write a method named sum that computes the total sum of all
elements in an array of integers.
– For now, just write a normal solution that doesn't use parallelism.

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
value 22 18 12 -4 27 30 36 50 7 68 91 56 2 85 42 98

// normal sequential solution


public static int sum(int[] a) {
int total = 0;
for (int i = 0; i < a.length; i++) {
total += a[i];
}
return total;
}
Parallelizing the algorithm
• Write a method named sum that computes the total sum of all
elements in an array of integers.
– How can we parallelize this algorithm if we have 2 CPUs/cores?

index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
value 22 18 12 -4 27 30 36 50 7 68 91 56 2 85 42 98

sum1 = 22+18+12+-4+27+30+36+50 = 191 sum2 = 7+68+91+56+2+85+42+98 = 449

sum = sum1 + sum2 = 640

– Compute sum of each half of array in a thread.


– Add the two sums together.
Initial steps
• First, write a method that sums a partial range of
the array:
// normal sequential solution
public static int sumRange(int[] a, int min, int max) {
int total = 0;
for (int i = min; i < max; i++) {
total += a[i];
}
return total;
}
Runnable partial sum
• Now write a runnable class that can sum a partial
array:
public class Summer implements Runnable {
private int[] a;
private int min, max, sum;

public Summer(int[] a, int min, int max) {


this.a = a;
this.min = min;
this.max = Math.min(max, a.length);
}

public int getSum() {


return sum;
}

public void run() {


sum = Sorting.sumRange(a, min, max);
}
}
Sum method w/ threads
• Now modify the overall sum method to run
Summers in threads:
// Parallel version (two threads)
public static int sum(int[] a) {
Summer firstHalf = new Summer(a, 0, a.length/2);
Summer secondHalf = new Summer(a, a.length/2, a.length);
Thread thread1 = new Thread(firstHalf);
thread1.start();
Thread thread2 = new Thread(secondHalf);
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException ie) {}
return firstHalf.getSum() + secondHalf.getSum();
}

You might also like