Sei sulla pagina 1di 7

Multithreading:

--------------
Multitasking:
---------------
Process Based :
--------------
executing several task simultaneously where each task is independent of
each other
ex: a java typing in a editor,listening to songs,download a file from
net all happens in the same system simultaneously.
these sort of multi tasking applicable at OS level.

Thread Based:
--------------
executing several task simultaneously where each part is sub-part of
the same program but independent of each other is called thread based multi tasking

each independent part is called thread.


best suitable at program level.

Purpose:
--------
To reduce cpu idle time to increase the performance and maximum
resource utilization.

Application Areas:
-------------------
Graphics
Gaming
web server and app servers..etc

Consider a program to search for a word in list of partitions.


C:,D: etc..

-----------------------------------------------------------------------------------
---------------------------------------
Defining a Thread:
-------------------

A thread is a separate flow of execution for every thread there is a job.

Two ways to define thread:


------------------------------

1.Extending Thread Class


2.Implementing Runnable Interface

Extending Thread Class:


-----------------------
class MyThread extends Thread {
@override
public void run(){
//Job of a Thread.
for(int i=0;i<10;i++){
System.out.println("Child Thread");
}
}
}
class DriverThread {
public static void main(String[] args){

//Thread Instantiation.
MyThread my = new MyThread();

//Starting of a Thread
my.start();
for(int i=0;i<5;i++){
System.out.println("Parent Thread");
}

}
}

we can define the Job inside run method.


Every java program has one main thread but internally many daemon threads are
there.
Main Thread creates the child thread object.
Main Thread starts child thread.

After my.start() --> There will be two jobs.


Main thread will execute the for loop inside main class and child class for loop
will be executed by child thread.

Thread Scheduler:
-----------------

It is the part of JVM and is responsible to schedule threads.


If multiple threads are waiting to get the chance of execution then In which order
threads will be executed is decided by thread scheduler.
we can expect the same order of execution every time.
hence there is no gurantee for exact output but we can provide several possible
op's.

===================================================================================
=============================================================
t.start() vs t.run();
----------------------

t.start():
----------
if we call this a separate thread will be created that will be responsible
for executing the run() method.
Here there will be two threads.
t.run():
---------
a separate thread won't be created.
main method will call the run() its like normal method call by main thread.
only one thread will be created.
-----------------------------------------------------------------------------------
-------------------------------------------------

Importance of Thread.start():
------------------------------

Is responsible to register the thread with ThreadScheduler and all other mandatory
activities.
Hence without thread.start method there is no chance of starting a new thread in
java.
Due to this it is the heart of Multithreading.
-----------------------------------------------------------------------------------
---------------

class MyThread extends Thread {


public void run(){
System.out.println("No-Args");
}
public void run(int i){
System.out.println("With-Args");
}
}
class DriverThread {
public static void main(){
MyThread mt = new MyThread();
mt.start();

}
}

By Default start() will call no-args run().


-----------------------------------------------------------------------------------
---------------------

If we dont have run() in our class by default Thread class run method will be
called which has no implementation.

Overriding of start():
------------------------
If we override start() then our start() will be executed like normal call and no
new thread wont be created which will never call run().

class MyThread extends Thread {


public void start(){
System.out.println("Start-Args");
}
public void run(){
System.out.println("With-Args");
}
}
class DriverThread {
public static void main(){
MyThread mt = new MyThread();
mt.start();
System.out.println("Main Thread");

}
}

It's not recommended to override start() method.

If we want to start method of Thread class then follow the code below.

class MyThread extends Thread {

public void start(){

super.start();
System.out.println("Start-Args");
}
public void run(){
System.out.println("With-Args");
}
}
class DriverThread {
public static void main(){
MyThread mt = new MyThread();
mt.start();
System.out.println("Main Thread");

}
}

===================================================================================
===================================================================================

Lifecycle of a Thread:
----------------------

MyThread mt = new MyThread(); ---> Thread Born/New State

mt.start() --> Ready/Runnable if Thread Scheduler allocates Process

run() ---> Running if run() completes.

Thread Dispose --> Dead

--------------------------------------------------------------

IllegalThreadState:
----------------------

class DriverThread {
public static void main(){
MyThread mt = new MyThread();
mt.start();
System.out.println("Main Thread");
mt.start()

}
}

After starting a thread if we start the thread once again then we will get
java.lang.IllegalThreadStateException
===================================================================================
===================================================================================
===================

Thread using Runnable:


---------------------------

Thread class already implements runnable interface


Its advised approach to define a Thread.

In the first approach our class always extends Thread class there is no chance of
extending any more which kills inheritance feature.
Runable(I)-->Thread-->MyThread

class MyRunnable implements Runnable {

public void run(){


//Job of a Thread.
for(int i=0;i<10;i++){
System.out.println("Child Thread");
}
}
}

class DriverThread {
public static void main(){
MyRunnable mt = new MyRunnable();
Thread t = new Thread(mt);
//mt--> Target Runnable
t.start();
System.out.println("Main Thread");
for(int i=0;i<10;i++){
System.out.println("Main Thread");
}

}
}

Case Study:
----------
MyRunnable mt = new MyRunnable();
Thread t1 = new Thread();
Thread t2 = new Thread(mt);

Case 1:
--------
t1.start();
New Thread will be created.
Default Thread class run() will be executed which has no implementation.
Case 2:
--------
t1.run();
No New Thread will be created.
Default Thread class run() will be executed which has no implementation.
Case 3:
--------
t2.start(mt);
New Thread will be created.
MyRunnable run() will be invoked and executed.
Case 4:
--------
t2.run();
MyRunnable run() will be executed which has no implementation and no new
thread.
Case 5:
--------
mt.start();
compile time exception.
-----------------------------------------------------------------------------------
-------------------
Thread Class Constructors:
-----------------------------

Thread t = new Thread();


Thread t = new Thread(Runnable r);
Thread t = new Thread(String name);
Thread t = new Thread(Runnable r, String name);
Thread t = new Thread(ThreadGroup g, String name);
Thread t = new Thread(ThreadGroup g, Runnable r);
Thread t = new Thread(ThreadGroup g, Runnable r, String name);
Thread t = new Thread(ThreadGroup g, Runnable r, String name, long stackSize);

-----------------------------------------------------------------------------------
-----------------------------------

Thread.currentThread().getName() --> To get name of the Thread


Thread.currentThread().setName(String name) --> To set our own Thread Name

-----------------------------------------------------------------------------------
---------------------

Thread Priority:
---------------

Thread.MIN_PRIORITY = 1
Thread.MAX_PRIORITY =10
Thread.NORMAL_PRIORITY=5

Thread scheduler will use priorities while allocating processor


Thread which is having highest priority will get the chance first
If two threads having same priority then we can't expect exact execution order.
It depends on thread scheduler.

public final void setPriority(int i); i<=10;


public final int getPriority();

Default Priority for all thread is 5.


-------------------------------------------------------

We can prevent a thread execution in 3 ways:

1.yeild()
2join()
3.sleep()

yeild():
----------

Potrebbero piacerti anche