Multi Threading Notes
Multi Threading Notes
-------------
Executing several tasks simultaneously is a concept of multitasking.
There are two types of multitasking
1.process based multitasking
2.Thread based multitasking
>> Whether it is Process based or Thread based the main objective of multitasking
is to reduce response time of the system and to improve performance.
>> The main important application areas of multithreading are
1. To develop multimedia graphics.
2. To develop animations.
3. To develop video games.
4. To develop web servers and applications servers etc.
>> When compared with old languages developing multithreaded applications in java
is very easy because java provides inbuilt support for multithreading with rich API
[Thread, Runnable, ThreadGroup...].
Thread:
-------
Thread is a flow/Process of execution or light weight process.
Defining a Thread:
-----------------
We can define a thread in the following two ways
1. By extending Thread class
2. By implementing Runnable interface
Case 2:
--------
Differenece between t.start() and t.run()
-----------------------------------------
In the case of t.start(), a new Thread will be created which is responsible for the
execution of run() method.
But, in the case of t.run() a new Thread won't be created and the run() method will
be executed by just like a normal method call by main Thread.
Hence in the above if we replace t.start() with t.run() then the output is
//Defining a Thread
class MyThread extends Thread{
@Override
public void run(){
for(int i = 0; i < 10; i++){
System.out.println("Child Thread");
}
}
}
output:
------
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
>> This output is executed by only Main Thread
Case 3:
--------
Importance of Thread class start() method
>> Thread class start() method is responsible to register the Thread with Thread
Schedular and all other mandatory activities.
>> Hence without executing Thread class start() method there is no chance of
starting a new Thread in Java.
>> Due to this, Thread class start() method is considered as heart of
multithreading.
start(){
1.Register this thread with Thread Schedular;
2.Perform all other mandatory activities;
3.Invoke run();
}
//Defining a Thread
class MyThread extends Thread{
//Overloaded methods
public void run(){
System.out.println("no-args run");
}
public void run(int i){
System.out.println("int arg run");
}
}
//Defining a Thread
class MyThread extends Thread{
//Defining a Thread
class MyThread extends Thread{
public void start(){
System.out.println("start method");
}
public void run(){
System.out.println("run method");
}
}
Case 9:
--------
After starting a Thread, if we are trying to restart the same thread then we will
get runtime exception saying IllegalThreadStateException.
===================================================================================
================================
Runnable(I) present in java.lang package and it contains only one method i.e.,
run() method.
//Defining a Thread
class MyRunnable implements Runnable{
public void run(){
//Job of Thread
for(int i = 0; i < 10; i++){
System.out.println("Child Thread");
}
}
}
class ThreadDemo{
public static void main(String[] args){
MyRunnable r = new MyRunnable();
Thread t = new Thread(r); // r -> target runnable
t.start();
for(int i = 0; i < 10; i++){
System.out.println("Main Thread");
}
}
}
Case Study:
------------
MyRunnable r = new MyRunnable();
Thread t1 = new Thread();
Thread t2 = new Thread(r);
Case 1: t1.start()
------------------
A new Thread will be created and which is responsible for the execution of Thread
class run() method, which has empty implementation.
Case 2: t1.run()
-----------------
No new Thread will be created and Thread class run() method will be executed just
like a normal method call.
Case 3: t2.start()
------------------
A new Thread will be created which is responsible for the execution of MyRunnable
class run() method.
Case 4: t2.run()
-----------------
A new Thread won't be created and MyRunnable class run() method will be executed
just like a normal method call.
Case 5: r.start()
-----------------
we will get compile time error saying MyRunnable class doesn't have start()
capability.
C-Error: Cannot find symbol method start() location class MyRunnable
-------
Case 6: r.run()
---------------
No new Thread will be created and MyRunnable class run() method will be executed
like normal method call.
===================================================================================
==============================
===================================================================================
===============================
}
class Test{
public static void main(String[] args){
System.out.println(Thread.currentThread().getName()); //main
MyThread t = new MyThread();
System.out.println(t.getName()); // Thread-0
Thread.currentThread().setName("theCodeExplore")
System.out.println(Thread.currentThread().getName()); //theCodeExplore
}
}
Output:
-------
run method executed by Thread Thread-0
main method executed by Thread main
Thread Priorities:
----------------------
* Every Thread in java has some priority, it may be default priority generated by
JVM or customised priority provided by programmer.
* The valid range of Thread priorities is 1 to 10, where 1 is MIN_PRIORITY and 10
is MAx_PRIORITY
Thread class defines the following constants to represent some standard priorities.
Thread.MIN_PRIORITY ----> 1
Thread.NORM_PRIORITY ----> 5
Thread.MAx_PRIORITY ----> 10
Thread class defines the following methods to get and set priority of a Thread
public final int getPriority()
public final void setPriority(int p) [allowed values range 1 to 10]
=========================================================================
Default Priority:
-----------------
The Dafault priority only for the main Thread is 5. But, for all remaining Threads
default priority will be inherited from parent to child i.e., whatever priority
parent Thread has the same priority will be there for the child Thread.
=============================================================================
class MyThread extends Thread{
public void run(){
for(int i = 0; i < 5; i++){
System.out.println("Child Thread");
}
}
}
class ThreadPriorityDemo{
public static void main(String[] args){
MyThread t = new MyThread();
t.setPriority(10); //[--line-1--]
t.start();
for(int i = 0; i < 5; i++){
System.out.println("Main Thread");
}
}
}
If we are commenting line-1, then both main and child threads have the same
priority 5. Hence, we can't expect execution order and exact output.
If we are not commenting line-1, then both main Thread has priority 5 and child
Thread has priority 10. Hence, child Thread will get chance first followed by main
Thread. In this case Output is
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Note:
-----
Some platforms won't provide proper support for Thread priorities.