Chapter 10 - Multi-Threading in Java
Chapter 10 - Multi-Threading 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()
{
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);
}
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
}
}
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
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
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