Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Tuesday, 20 January 2015

What is sleep() method in Thread Class

Sleeping a thread (sleep() method):

The sleep() method of Thread class is used to sleep a thread for the specified time.

Syntax of sleep() method:

The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds) throws InterruptedException
public static void sleep(long miliseconds, int nanos) throws InterruptedException


Example of sleep method:

class Test extends Thread{
public void run(){
for(int a=1;a<6;a++){
try{
Thread.sleep(500);
}
catch(InterruptedException ex){
System.out.println(ex);
}
System.out.println(a);
}
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.start();
t2.start();
}
}

Output:
1
1
2
2
3
3
4
4
5
5
6
6

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread to run and so on.

Can we start a thread twice ?

No. After staring a thread,it can never be started again.If you does so, an IllegalThreadStateException is thrown.
For Example:

class Test extends Thread{
public void run(){
System.out.println("this is run method");
}
public static void main(String []args){
Multi t1=new Multi();
t1.start();
t1.start();
}
}

Output: this is run method
Exception in thread "main" java.lang.IllegalThreadStateException


What if we call run() method directly instead start() method ?

Each thread starts in a separate call stack.
Invoking the run() method from main thread,the run() method goes onto the current call stack rather than at the beginning of a new call stack.

class Test extends Thread{
public void run(){
System.out.println("this is run method");
}
public static void main(String []args){
Test t1=new Test();
t1.run();  //fine it will run , but does not start a separate call stack
}
}

Output: this is run method

Problem if you direct call run() method:

class Test extends Thread{
public void run(){
for(int a=1;a<6;a++){
try
{
Thread.sleep(500);
}
catch(InterruptedException ex){
System.out.println(ex);}
System.out.println(a);
 }
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.run();
t2.run();
}
}

Output:
1
2
3
4
5
1
2
3
4
5
6


Note: As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not a thread object.





What are the Methods of Thread Class

The join() method:

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.

Syntax:

public void join() throws InterruptedException
public void join(long miliseconds) throws InterruptedException

For Example:

class Test extends Thread{
public void run(){
for(int a=1;a<=6;a++){
try{
Thread.sleep(500);
}catch(Exception ex){
System.out.println(ex);
}
System.out.println(a);
}
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
try{
t1.join();
}catch(Exception ex){
System.out.println(ex);
}
t2.start();
t3.start();
}
}

Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
6
6

As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.

Example of join(long miliseconds) method:

class Test extends Thread{
public void run(){
for(int a=1;a<=5;a++){
try{
Thread.sleep(500);
}catch(Exception ex){System.out.println(ex);}
System.out.println(i);
}
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
try{
t1.join(1500);
}
catch(Exception ex){
System.out.println(ex);}
t2.start();
t3.start();
}
}

Output:
1
2
3
1
4
1
2
5
2
3
3
4
4
5
5


In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.

getName(), setName(String) and getId() method of Thread class:

public String getName()
public void setName(String name)
public long getId()

class Test extends Thread{
public void run(){
System.out.println("this is run method");
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Vishwa Singh");
System.out.println("After changing name of t1:"+t1.getName());
}
}

Output: Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
this is run method
After changling name of t1:Vishwa Singh
this is run method


The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.
Syntax:

public static Thread currentThread()

Example of currentThread() method:

class Test extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
t1.start();
t2.start();
}
}

Output: Thread-0
Thread-1


Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specifification that which sheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

Example of priority of a Thread:

class Test extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}

Output: running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1


Monday, 19 January 2015

What is Daemon Thread in Java

Daemon Thread:

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:

It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
Its life depends on user threads.
It is a low priority thread.

Why JVM termintates the daemon thread if there is no user thread remaining ?

The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Daemon thread:

The java.lang.Thread class provides two methods related to daemon thread

public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
public boolean isDaemon(): is used to check that current is daemon.

Example of Daemon thread:

class Test extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.setDaemon(true);
t1.start();
t2.start();
}
}

Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false


Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

class Test extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.start();
t1.setDaemon(true);  //will throw exception here
t2.start();
}
}

Output: exception in thread main: java.lang.IllegalThreadStateException

What is Thread Schedular

Thread Schedular 

The thread scheduler is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread schedular.
On.ly one thread at a time can run in a single process.
The thread schedular mainly uses preemptive or time slicing scheduling to schedule the threads.

What is the difference between preemptive scheduling and time slicing ?

Under preemptive scheduling , the highest priority task executes until it enters the waiting or dead states or
a higher priority task comes into existence. Under time slicing , a task executes for a predefined slice of timeand then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

What is Multitasking in Java

Multitasking:

Performing multiple task at the same time is know as Multitasking.

How to perform single task by multiple threads ?

If you have to perform single task by many threads, have only one run() method.
For example:
>1. Program of performing single task by multiple threads.

class Test extends Thread{
public void run(){
System.out.println("this is task one");
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
t2.start();
t3.start();
}
}

Output: this is task one
        this is task one
        this is task one

       
>2. Program of performing single task by multiple threads.

class Test implements Runnable{
public void run(){
System.out.println("this is task one");
}
public static void main(String []args){
Thread t1 =new Thread(new Test());  //passing annonymous object of Test class
Thread t2 =new Thread(new Test());
t1.start();
t2.start();
 }
}   

Output: this is task one
        this is task one


Note: Each thread run in a separate callstack.   

How to perform multiple tasks by multiple threads (multtasking in multithreading) ?   

If you have to perform multiple tasks by multiple threads,you have to use multiple run() methods.
For example:
>1. Program of performing two tasks by two threads:

class Test1 extends Thread{
public void run(){
System.out.println("this is task one");
}
}
class Test2 extends Thread{
public void run(){
System.out.println("this is task two");
 }
}
class Test{
public static void main(String []args){
Test1 t1=new Test1();
Test2 t2=new Test2();
t1.start();
t2.start();
 }
}

Output: this is task one
        this is task two

       
Same example as above by annonymous class that extends Thread class:

>2. Program of performing two tasks by two threads

class Test{
public static void main(String []args){
Thread t1=new Thread(){
public void run(){
System.out.println("this is task one");
 }
};
Thread t2=new Thread(){
public void run(){
System.out.println("this is task two");
}
};
t1.start();
t2.start();
}
}

Output: this is task one
        this is task two


Same example as above by annonymous class that implements Runnable interface:       

>3. Program of performing two tasks by two threads

class Test{
public static void main(String []args){
Runnable r1=new Runnable(){
public void run(){
System.out.println("this is task one");
}
};
Runnable r2=new Runnable(){
public void run(){
System.out.println("this is task two");
}
};
Thread t1=new Thread(r1);
Thread t2=new Thread(r1);
t1.start();
t2.start();
}
}

Output: this is task one
       this is task two
      

      
Next---> What is Thread Schedular in Java
       
       
       

How to create Thread in Java


In java there are two ways,you can create a thread:

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

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)

Note: If you want to see how many methods,constructors and variables in a class or interface then you just type below commnad on CMD.

     i.e. javap whole_package_name.Class_Name. 
     //  javap java.lang.Thread
     // javap java.lang.Runnable

   
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.
>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.
>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   


Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

Note: Runnable interface is also know as functional interface.(A interface which has only one method)

public void run():  is used to perform action for a thread.

Starting a thread:

start()  method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.

>1. Creating thread By extending Thread class:

class Test extends Thread{
public void run(){
System.out.println("thread is in running state");
}
public static void main(String []args){
Test t=new Test();
t.start();
 }
}

Ouput: thread is in running state

Who makes your class object as thread object ?

Thread class constructor allocates a new thread object.When you create object of Test class,your class constructor is invoked(provided by Compiler) from where Thread class constructor is invoked(by super() as first statement).So your Test class object is thread object now.

>2. Creating thread By implementing the Runnable interface:

class Test implements Runnable{
public void run(){
System.out.println("thread is in running state");
}
public static void main(String []args){
Test t=new Test();
Thread th =new Thread(t);
th.start();
 }
}

Output: thread is in running state

Note: If you are not extending the Thread class, your class object would not be treated as a thread object.So you need to explicitly create  Thread class object.We are passing the object of your class that implements Runnable so that your class run() method can execute.


 Next---> What is Multitasking in Java

What is life cycle of a Thread in Java

Life cycle of a Thread:

A thread can be in one of the five states in the thread.According to sun, there is only 4 states new, runnable, non-runnable and terminated.
There is no running state. But for better understanding of the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM.  The thread states are given below:

>1. New
>2. Runnable
>3. Running
>4. Non-Runnable (Blocked)
>5. Terminated

>1. New:

A thread is in new state if you create an instance of Thread class but before the invocation of start() method
i.e. Thread th=new Thread();

>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.
i.e. th.start();

>3. Running:

The thread is in running state if the thread scheduler has selected it means run() method call on that thread.
i.e. th.start();
     th.run();
   
>4. Non-Runnable (Blocked):

This is the state when the thread is still alive, but is currently not eligible to run.It is in blocked state or sleep or wait or in suspend state.
i.e. th.wait();

>5. Terminated:

A thread is in terminated or dead state when its run() method exits means on calling destroy() method
i.e. th.destroy();

Next--->How to create Thread in Java
   

What is Multithreading in Java

Multithreading in Java:

Multithreading is a process of executing multiple threads simultaneously.Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and contextswitching between the threads takes less time  than processes. Multithreading is mostly used in games, animation etc.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

>1. Process-based Multitasking(Multiprocessing)
>2. Thread-based Multitasking(Multithreading)

>1.Process-based Multitasking (Multiprocessing)

Each process have its own address in memory i.e. each process allocates seprate memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

>2. Thread-based Multitasking (Multithreading)

Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread ?

A thread is a lightweight subprocess, a smallest unit of processing. It has a separate path of execution. It shares the memory area of process.
Thread is executed inside the process. There is context-switching between the threads.
There can be multiple processes inside the OS and one process can have multiple threads.

Note: At a time only one thread is executed.

Next---> What is life cycle of a Thread