0% found this document useful (0 votes)
21 views10 pages

Multithreading

The document discusses different types of multitasking and ways to define and control threads in Java. It covers process-based and thread-based multitasking, defining threads by extending the Thread class and implementing Runnable, and key methods like start() and run(). The document also examines thread scheduling, life cycles, and best practices.

Uploaded by

Harshavardhan GR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views10 pages

Multithreading

The document discusses different types of multitasking and ways to define and control threads in Java. It covers process-based and thread-based multitasking, defining threads by extending the Thread class and implementing Runnable, and key methods like start() and run(). The document also examines thread scheduling, life cycles, and best practices.

Uploaded by

Harshavardhan GR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Introduction:

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

Multitasking: Executing several tasks simultaneously is the concept of


multitasking.

There are two types of multitasking's.

1. Process based multitasking.


2. Thread based multitasking.

Process based multitasking:


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

Executing several tasks simultaneously where each task is a separate


independent process, such type of multitasking is called process
based multitasking.

Example:
----------
> While typing a java program in the editor we can able to listen mp3 audio songs
at the same time we can download a file from the net all these tasks are
independent of each other and executing simultaneously and hence it is Process
based multitasking.
> This type of multitasking is best suitable at "os level".

Thread based multitasking:


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

Executing several tasks simultaneously where each task is a separate


independent part of the same program, is called Thread based multitasking.
And each independent part is called a "Thread".

> This type of multitasking is best suitable for "programatic level".

The main important application areas of multithreading are:

1. To implement multimedia graphics.


2. To develop animations.
3. To develop video games etc.
4. To develop web and application servers
5. Whether it is process based or Thread based the main objective of
multitasking is to improve performance of the system by reducing response
time.

The ways to define instantiate and start a new Thread:


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

We can define a Thread in the following 2 ways.


1. By extending Thread class.
2. By implementing Runnable interface

Defining a Thread by extending "Thread class":


---------------------------------------------------------
Example:

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}
}

class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();//Instantiation of a Thread
t.start();//starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}

Case 1: Thread Scheduler:


--------------------------------
> If multiple Threads are waiting to execute then which Thread will execute 1st is
decided by "Thread Scheduler" which is part of JVM.
> Which algorithm or behavior followed by Thread Scheduler we can't expect
exactly it is the JVM vendor dependent hence in multithreading examples we
can't expect exact execution order and exact output.

Case 2: Difference between t.start() and t.run() methods:


-----------------------------------------------------------
> 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() no new Thread will be created and run() method will be
executed just like a normal method by the main Thread.
> In the above program if we are replacing t.start() with t.run() the following is
the
output.

Output:
-------------
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
Entire output produced by only main Thread.
Case 3: importance of Thread class start() method:
---------------------------------------------------------
For every Thread the required mandatory activities like registering the Thread with
Thread Scheduler will takes care by Thread class start() method and programmer is
responsible just to define the job of the Thread inside run() method.
That is start() method acts as best assistant to the programmer.

Example:
------------
start()
{
1. Register Thread with Thread Scheduler
2. All other mandatory low level activities.
3. Invoke or calling run() method.
}
We can conclude that without executing Thread class start() method there is no
chance
of starting a new Thread in java. Due to this start() is considered as heart of
multithreading.

Case 4: If we are not overriding run() method:


------------------------------------------------
If we are not overriding run() method then Thread class run() method will be
executed
which has empty implementation and hence we won't get any output.

Example:
-----------
class MyThread extends Thread
{
}

class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}
It is highly recommended to override run() method. Otherwise don't go for
multithreading concept.

Case 5: Overloding of run() method:


-----------------------------------------
We can overload run() method but Thread class start() method always invokes no
argument run() method the other overload run() methods we have to call explicitly
then
only it will be executed just like normal method.

Example:
--------------
class MyThread extends Thread
{
public void run()
{
System.out.println("no arg method");
}
public void run(int i)
{
System.out.println("int arg method");
}
}

class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}

Output:
------------
No arg method

Case 6: overriding of start() method:


---------------------------------------------
If we override start() method then our start() method will be executed just like a
normal
method call and no new Thread will be started.

Example:
----------------
class MyThread extends Thread
{
public void start()
{
System.out.println("start method");
}
public void run()
{
System.out.println("run method");
}
}

class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
System.out.println("main method");
}
}

Output:
--------------
start method
main method

Entire output produced by only main Thread.


Note : It is never recommended to override start() method.

Life Cycle of a Thread:


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

> Once we created a Thread object then the Thread is said to be in new state or
born state.
> Once we call start() method then the Thread will be entered into Ready or
Runnable state.
> If Thread Scheduler allocates CPU then the Thread will be entered into running
state.
> Once run() method completes then the Thread will entered into dead state.

Case 7:
--------
After starting a Thread we are not allowed to restart the same Thread once again
otherwise we will get runtime exception saying "IllegalThreadStateException".

Example:
-----------
MyThread t=new MyThread();
t.start();//valid
t.start();//we will get R.E saying: IllegalThreadStateException

Defining a Thread by implementing Runnable interface:


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

We can define a Thread even by implementing Runnable interface also.


Runnable interface present in java.lang.pkg and contains only one method run().

class MyRunnable implements Runnable


{
public void run()
{
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);//here r is a Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}

Output:
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
We can't expect exact output but there are several possible outputs.

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 which is responsible for the execution of Thread class
run()method.

Output:
---------------
main thread
main thread
main thread
main thread
main thread

Case 2: t1.run():
----------------------
No new Thread will be created but Thread class run() method will be executed just
like
a normal method call.

Output:
--------------
main thread
main thread
main thread
main thread
main thread

Case 3: t2.start():
-----------------------
New Thread will be created which is responsible for the execution of MyRunnable
run()
method.

Output:
-----------------
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread

Case 4: t2.run():
--------------------
No new Thread will be created and MyRunnable run() method will be executed just
like
a normal method call.

Output:
-----------------
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread

Case 5: r.start():
--------------------
We will get compile time error saying start()method is not available in MyRunnable
class.

Output:
------------
Compile time error

ThreadDemo.java:18: cannot find symbol


Symbol: method start()
Location: class MyRunnable

Case 6: r.run():
----------------------
No new Thread will be created and MyRunnable class run() method will be executed
just like a normal method call.

Output:
--------------
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread
Best approach to define a Thread:
------------------------------------

> Among the 2 ways of defining a Thread, implements Runnable approach is


always recommended.
> In the 1st approach our class should always extends Thread class there is no
chance of extending any other class hence we are missing the benefits of
inheritance.
> But in the 2nd approach while implementing Runnable interface we can extend
some other class also. Hence implements Runnable mechanism is recommended
to define a Thread.

Thread class constructors:


----------------------------
1. Thread t=new Thread();
2. Thread t=new Thread(Runnable r);

Getting and setting name of a Thread:


--------------------------------------------
> Every Thread in java has some name it may be provided explicitly by the
programmer or automatically generated by JVM.
> Thread class defines the following methods to get and set name of a Thread.

Methods:
----------
1. public final String getName()
2. public final void setName(String name)

Example:
----------------
class MyThread extends Thread
{}

class ThreadDemo
{
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("Bhaskar Thread");
System.out.println(Thread.currentThread().getName());//Bhaskar Thread
}
}

Note: We can get current executing Thread object reference by using


Thread.currentThread() method.

Thread Priorities:
---------------------

> Every Thread in java has some priority it may be default priority generated by
JVM (or) explicitly provided by the programmer.
> The valid range of Thread priorities is 1 to 10[but not 0 to 10] where 1 is the
least
priority and 10 is highest priority.
> Thread class defines the following constants to represent some standard
priorities.
1. Thread. MIN_PRIORITY----------1
2. Thread. MAX_PRIORITY----------10
3. Thread. NORM_PRIORITY--------5
> Thread scheduler uses these priorities while allocating CPU.
> The Thread which is having highest priority will get chance for 1st execution.
> If 2 Threads having the same priority then we can't expect exact execution order
it depends on Thread scheduler whose behavior is vendor dependent.
> We can get and set the priority of a Thread by using the following methods.
1. public final int getPriority()
2. public final void setPriority(int newPriority);//the allowed values are 1
to 10
> The allowed values are 1 to 10 otherwise we will get runtime exception saying
"IllegalArgumentException".

Default priority:
---------------------

The default priority only for the main Thread is 5. But for all the remaining
Threads
the default priority will be inheriting from parent to child. That is whatever the
priority
parent has by default the same priority will be for the child also.

Example 1:
-----------------
class MyThread extends Thread
{}

class ThreadPriorityDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getPriority());//5
Thread.currentThread().setPriority(9);
MyThread t=new MyThread();
System.out.println(t.getPriority());//9
}
}

Example 2:
-------------------------
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}
}

class ThreadPriorityDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
//t.setPriority(10); //----> 1
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}

> If we are commenting line 1 then both main and child Threads will have the
same priority and hence we can't expect exact execution order.
> If we are not commenting line 1 then child Thread has the priority 10 and main
Thread has the priority 5 hence child Thread will get chance for execution and
after completing child Thread main Thread will get the chance in this the output
is:

Output:
----------------
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread

The Methods to Prevent a Thread from Execution:


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

We can prevent(stop) a Thread execution by using the following methods.


1. yield();
2. join();
3. sleep();

You might also like