Multithreading
Multithreading
================================
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".
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");
}
}
}
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.
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.
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
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
> 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
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:
----------------------------------
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
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:
------------------------------------
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
}
}
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