Sunday 30 April 2017

8. Thread priorities and yield()


1. Thread priorities
1.       Every thread in java has some priority, it may be default priority or custom priority.
2.       Thread priority range is 1 to 10.(Min priority = 1, Max priority = 10)
3.       Thread class contains constant values
a.       Thread.MIN_PRIORITY = 1
b.      Thread.NORM_PRIORITY = 5
c.       Thread.MAX_PRIORITY = 10
4.       Thread Scheduler will use priorities while allocating processor.
5.       The thread which is having highest priority will get the chance first to execute.
6.       If two threads having same priority then we can’t expect exact execution order, it depends on Thread Scheduler.
7.       Thread.setPriority(int); for setting priority to thread. Allowed values range is 1 to 10, other than this range, it will throw IlligalArgumentException.
2. How thread priorities will work
1.       The default priority only for main thread is 5, but all remaining thread default priority inherited from parent to child.
2.       Whatever priority parent thread has, the same priority will be there for child thread by default.
3.       Some OS /Platforms won’t provide support for thread priorities.
4.    After thread created and in middle of execution also we can change the thread priority.
public class MyThread implements Runnable {
  public void run() {
        System.out.println("HI”);
  }
  public static void main(String[] args) {
        MyThread runnable = new MyThread();
        Thread.currentThread().setPriority(7);
        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println(thread.getPriority());//7
  }
}
3. How many ways to stop the execution of thread temporarily  
1.       Following Thread class methods are stop the execution of a thread temporarily.
a.       yield()
b.      join()
c.       sleep()
4. Thread class yield()  usage
1.       yield() causes to pause current executing thread to give the chance for waiting threads of same priority or high priority.
2.       If there is no waiting thread or all waiting threads have low priority then same thread can continue its execution.
3.       If multiple threads are waiting with same priority then which waiting thread will get the chance we can’t expect it depends on thread scheduler.
4.       The thread which is yielded, when it will get chance once again it depends on Thread scheduler.
5.       Syntax of yield()
public   static   native   void   yield();
6.       Once Thread.yield() is called , then thread will go to Runnable state.
7.    A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
public class MyThread implements Runnable {
  public void run() {
        for(int i=0; i<10; i++){
          System.out.println(“child thread”);
          Thread.yield();
        }
  }
  public static void main(String[] args) {
        MyThread runnable = new MyThread();
        Thread thread = new Thread(runnable);
        thread.start();
        for(int i=0; i<10; i++){
          System.out.println(“main thread”);
        }}}
7.       In the above program if we are commenting Thread.yield() , than both the threads will be executed simultaneously and we can’t expecting which thread will complete first.
8.       If we are not commenting Thread.yield() than child thread always calls yield() because of that main thread will get chance more number of times and the chance of completing main thread first is high.
9.       Yield() is native method , so its not implemented in java, it needs support from underlying OS.
10.   Some platforms won’t provide proper support for yield().So we can’t expect  it always pauses the current thread.
11. If we call yield() than current thread will stop its execution and it will go to ready state(if and only if same or high priority thread is exists).
4. Can we yield() particular thread by calling yield() using thread object instead of Thread class
  1. No, we can’t call yield() of a particular thread, but we can call yield() using any thread object.
  2. There is no difference between below 3 statements will yield the currently executing thread only.
    1. Thread.yield()   → Currently executing thread will be yielded.
    2. t1.yield()   → Currently executing thread will be yielded, not t1 thread.
    3. t2.yield()   → Currently executing thread will be yielded, not t2 thread.



Saturday 29 April 2017

7. Thread Lifecycle

1. Thread Lifecycle.
  • A java thread can be in any of following thread states during it’s life cycle i.e. New, Runnable, Blocked, Waiting, Timed Waiting or Terminated.
  • These are also called life cycle events of a thread in java.




Java Code
Thread State
MyThread thread = new MyThread();
New
thread.start();
start() logic Thread Scheduler will allocates
space and executes run()
Runnable
Calling blocking methods
wait(), join(),
Wait
Synchronized area
Blocked
wait(ms), sleep(ms)
TIMED WAITING
completion of run()
Terminated / Dead


1.  New/Born
  • As soon as, you create new thread, it’s in NEW state.
  • It remains in this state until the program starts the thread using it’s start() method.                 MyThread thread = new MyThread();
  • At this point, thread is not alive and it’s a state internal to Java programming.
2. Runnable ~ Ready + Running
  • Calling start() method on thread put it in RUNNABLE state.
  • At this point, execution control is passed to thread scheduler to finish it’s execution.
  • Thread scheduler decide from this point that this thread should be executed or should be put on hold to give chance to other runnable threads.
  • Thread scheduling is platform dependent — the behavior of a multi-threaded program could vary across different Java implementations.
  • In most operating systems, each thread is given a small amount of processor time is called a quantum or timeslice with which to perform its task.
  • A task utilizing it’s quantum is said to be in RUNNING state.
  • When its quantum expires, the thread returns to the RUNNABLE state, and the operating system assigns another thread to the processor.
  • The process that an operating system uses to determine which thread to execute is called thread scheduling and is dependent on thread priorities.
  • The operating system hide the RUNNABLE and RUNNING states from the Java Virtual Machine (JVM), which sees only the RUNNABLE state.
3. Blocked
  • A RUNNABLE thread transitions to the BLOCKED state when it attempts to perform a task that cannot be completed immediately and it must temporarily wait until that task completes.
  • For example, when a thread issues an input/output request, the operating system blocks the thread from executing until that I/O request completes.
  • At that point, the blocked thread transitions to the RUNNABLE state, so it can resume execution. A blocked thread cannot use a processor, even if one is available.
  • If Synchronized areas also threads will block for locks.
4. Waiting
  • A thread can be put in waiting state for various reasons e.g. calling it’s wait(), join() method.
  • Usually program put a thread in WAIT state because something else needs to be done prior to what current thread is doing.
  • Once the thread wait state is over or it is, it’s state is changed to RUNNABLE and it’s moved back to thread pool.
5. Timed Waiting
  • A RUNNABLE thread can transition to the TIMED WAITING state if it provides an optional wait interval when it’s waiting for another thread to perform a task.
  • You can put a java thread in TIMED WAITING state by calling it’s sleep(long millis) method or wait(long millis) method.
  • Such a thread returns to the RUNNABLE state when it’s notified by another thread or when the timed interval expires whichever comes first.
  • Timed waiting threads and waiting threads cannot use a processor, even if one is available.
6. Terminated
  • A thread enters the TERMINATED state (sometimes called the dead state) when it successfully completes its task or otherwise terminated due to any error or even it was forcefully killed.


2. How to print Thread state.
  • By calling getState() from thread object to get state of the thread.
  • In thread class given inbuilt enum for thread states for comparison.
  • If we want to write the logic according to the thread state then
    if(t1.getState().toString() == “TIMED_WAITING”){........}
  • In above case we need to convert state to string, it is waste of time, so java given one more way to compare thread states.
  • Thread.State is the enum name.
    if(Thread.State.TIMED_WAITING   ==  t1.getState()){...}
3. Sample program for printing thread states.


public class ThreadDemo extends Thread{

public void run() {
System.out.println("i am in run() "+Thread.currentThread().getName());
try {
this.join(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
m();
System.out.println("end of run() "+Thread.currentThread().getName());
}
synchronized void m(){
try {
Thread.sleep(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getState());
}

public static void main(String[] args) throws InterruptedException {

ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
t1.start();
t2.start();
Thread.sleep(5000l);
System.out.println("t1 "+t1.getState());
System.out.println(Thread.State.TIMED_WAITING ==t2.getState());
}

}



3. Java Program to create Binary Tree