Thread in Java

Thread-
A thread is the program's path of execution.
A Thread is the subset of the process, A Process run on different memory space, But all the thread shared the same memory space, in this memory space each thread have its own Stack Memory


Life Cycle of Thread
Life Cycle of the thread is controlled by the JVM
A thread can have only one of the following state
1-New
2-Runnable
3-Running
4-Non Runnable or(Blocked)
5-Terminated

Creation of the thread
Thread can be created using 2 Methods
1-By extends Thread Class

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

}  
//Create new object of this class and start method is called to execute the run

2-By implementing Runnable interface

class MultiThreading  implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
MultiThreading  m1=new MultiThreading ();  
//Creating the Job For the Thread
Thread t1 =new Thread(m1);  //Passing the Job two the thread
t1.start();   //Executing the Job
 }  

}  
//in this a single job means the object of runnable implementer can be passed to various thread

Note- For both the case you have to override the Run() method
  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)


Thread is Scheduled by the JVM

Sleep() Method and wait() method
it is provided in the thread class 
  • public static void sleep(long miliseconds)throws InterruptedException
  • public static void sleep(long miliseconds, int nanos)throws InterruptedException
Note-sleep() does not release any lock or monitor while waiting,
 wait() is used to release lock or monitor while waiting.
wait() is used for the inter thread communication
sleep() is only used for a pause while executing.
sleep() goes for a particular amount of time, while wait() goes for indefinite amount and only comes back when you call notify() or notifyAll()
Note-sleep is a static method, so even if you call anotherThread.sleep(), the currently executing thread will sleep, no impact on the anotherThread 

Remark a twist-
You have an lock and you are inside the synchronized block means you have an lock on object and you call on wait() method
BUT BUT wait() is called on an object not on the thread-
So while calling the wait() the thread must acquire the lock on that object 
and after calling wait releases the lock on object 
 Now the another thread will get access the lock on the same object and and till that he calls notify the previously will be on waiting.

wait() and notify() or notifyAll()
sleep and interrupt()


java.lang.IllegalMonitorStateException – 
1-Try to start same thread twice
2-You are calling the wait or notify without having the lock on  object 
3- when you simply call wait() it is only successful if you already took lock on this

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.

 t1.start();
   try{ 
   t1.join();  
 }catch(Exception e){System.out.println(e);}  

now the main thread wait till t1 starts and t1 finishes 

Thread Priority-
int from 1 to 10, thread scheduler schedules the thread according to its priority, 
BUT NO GUARANTEE 

3 Constant defined in Thread CLass
  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY
Daemon thread in Java
low priority thread, provide service to user thread, like gc, finalizer etc 
t1.setDaemon(true) or isDaemon()
JVM does not cares about these thread if user thread finishes JVM never wait to finish these thread

Why wait and notify is present in the object class?
Locks are made available on the basis of the object.
That's the reason of of these method call can only be performed from synchronized Block

ThreadGroup
ThreadGroup tg1 = new ThreadGroup("Name of ThreadGroup");  
Thread t1 = new Thread(tg1, runnable,"one");
and many methods in threadgrop to list or destroy other thread.

CountDownLatch-
java.util.concurrent.CountDownLatch is a concurrency construct that allows one or more threads to wait for a given set of operations to complete.

CountDownLatch is initialized with a given count.
CountDownLatch latch = new CountDownLatch(3);
The count is decremented by each time when you call countDown() method

Threads waiting for this count to reach zero can call one of the await() methods
latch.await(); 
 // latch is the CountDownLatch  object which is member of the class
//which implements runnable.called from run method
Calling await()blocks the thread until the count reaches zero
this.latch.countDown();
// this is also from run method of another class which implements runnable 
the latch of same object is passed to both for await and for countDown

One of the major disadvantages of this we cannot reuse the countDownLatch when its hits 0
Take a reference from 


CyclicBarrier- 
used to perform the final part of task, when individual task are completed.
All threads which wait for each other to reach barrier are called parties,
CyclicBarrier is initialized with number of parties to be wait


final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                //This task will be executed once all thread reaches barrier
                System.out.println("All parties are arrived at barrier, lets play");
            }
        });

threads wait for each other by calling CyclicBarrier.await() method 

Create three thread passed the same CyclicBarrier object as a constructor argument of the class which implements runnable 

and from run methods of this class call await methods, with the object that is passed in the constructor at the time of creation of runnable implements class

CyclicBarrier.await() is a blocking method in Java and  blocks until all Thread or parties call await()

Difference between CountDownLatch and CyclicBarrier in Java
1-you can reuse CyclicBarrier by calling reset() method not countdownlatch



Why Thread.stop() is Deprecated.
stopping a thread would not be an easy process
Thread has many of its child process or thread which originates from it.
Thread has its own stack
it has many locks acquired, may have own file or a socket connection
or may be in between the writing the file or transferring the stream of bits to the network

and you are killing it by shooting in its head, it may lead to many corrupted thing 
There are co-operative mechanism to do so called interruption


Comments