Tuesday, 4 March 2014

Add thread to Thread Group

Thread class provides 4 constructors to add threads to Thread groups.

1. public Thread(ThreadGroup group, String name)
Create a new thread with the specific name and add it to the group.

2. public Thread(ThreadGroup group,Runnable target)
Creates a new thread for the Runnable target and place it in a specific group.

class ThreadGroupEx implements Runnable{
 public void run(){
  Thread t = Thread.currentThread();
  System.out.println("My Name is " + t.getName() + " I am in group" + t.getThreadGroup() );
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("Group1");
  ThreadGroupEx task1 = new ThreadGroupEx();
  ThreadGroupEx task2 = new ThreadGroupEx();

  Thread t1 = new Thread(group1, task1);
  Thread t2 = new Thread(group1, task2); 

  t1.start();
  t2.start();

  t1.join();
  t2.join();
 }
}
 
Output
My Name is Thread-1 I am in groupjava.lang.ThreadGroup[name=Group1,maxpri=10]
My Name is Thread-0 I am in groupjava.lang.ThreadGroup[name=Group1,maxpri=10]
     
3. public Thread(ThreadGroup group, Runnable target, String name)
Creates a new thread for the Runnable target, assign a specific name and place it in a specific group.

class ThreadGroupEx implements Runnable{
 public void run(){
  Thread t = Thread.currentThread();
  System.out.println("My Name is " + t.getName() + " I am in group" + t.getThreadGroup() );
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("Group1");

  ThreadGroupEx task1 = new ThreadGroupEx();
  ThreadGroupEx task2 = new ThreadGroupEx();

  Thread t1 = new Thread(group1, task1, "Thread1");
  Thread t2 = new Thread(group1, task2, "Thread2"); 

  t1.start();
  t2.start();

  t1.join();
  t2.join();
 }
}
    
Output
My Name is Thread2 I am in groupjava.lang.ThreadGroup[name=Group1,maxpri=10]
My Name is Thread1 I am in groupjava.lang.ThreadGroup[name=Group1,maxpri=10]
    
4. public Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Creates a new thread for the Runnable target, assign a specific name and place it in a specific group. Stack size for the stack specified in bytes. The effect of stack size is totally platform dependent.

For more information on stack size see the below post.
http://selflearningjava.blogspot.in/2014/02/stack-memory.html

You are free to give any value to the stackSize variable, but it is totally the virtual machine decides. For Example If you given very minimum value for the stack, then Virtual Machine, makes it as Platform specific minimum value, If you given very maximum value, then Virtual Machine makes it as Platform specific maximum value.

Specifying a value of zero for the stackSize parameter will cause this constructor to behave exactly like the Thread(ThreadGroup, Runnable, String) constructor.

class ThreadGroupEx implements Runnable{
 public void run(){
  Thread t = Thread.currentThread();
  System.out.println("My Name is " + t.getName() + " I am in group" + t.getThreadGroup() );
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("Group1");
  ThreadGroupEx task1 = new ThreadGroupEx();
  ThreadGroupEx task2 = new ThreadGroupEx();

  Thread t1 = new Thread(group1, task1, "Thread1", 1000);
  Thread t2 = new Thread(group1, task2, "Thread2", 2000); 

  t1.start();
  t2.start();

  t1.join();
  t2.join();
 }
}
   
Output

My Name is Thread1 I am in groupjava.lang.ThreadGroup[name=Group1,maxpri=10]
My Name is Thread2 I am in groupjava.lang.ThreadGroup[name=Group1,maxpri=10]




Create Thread group                                                 Get parent thread group                                                 Home

Create a Thread Group

ThreadGroup class provides two constructors to create a thread group.

1. public ThreadGroup(String name)
Constructs a new thread group. The parent of this new group is the thread group of the currently running thread.

class ThreadEx{
 public static void main(String args[]){
  ThreadGroup group1 = new ThreadGroup("Group1");

  System.out.println("Thread Group Name is " + group1.getName());
  System.out.println("Parent group of the new Thread group is " + group1.getParent().getName());
 }
}

Output
Thread Group Name is Group1
Parent group of the new Thread group is main

As you observe, the new thread group created in the main method, Which runs in main thread and main thread is part of main thread group. So the parent for the new thread group is “main”. GetParent() returns the parent group of the current thread group. GetName() returns the thread group name.

2. public ThreadGroup(ThreadGroup parent, String name)
Creates a new thread group. The parent of this new group is the specified thread group.   

class ThreadEx{
 public static void main(String args[]){
  ThreadGroup group1 = new ThreadGroup("Group1");
  ThreadGroup group2 = new ThreadGroup(group1, "Group2");

  System.out.println("Thread Group group2 parent is " + group2.getParent().getName());
  System.out.println("Thread Group group1 parent is " + group1.getParent().getName());
 }
}

Output
Thread Group group2 parent is Group1
Thread Group group1 parent is main
   


Thread Groups                                                 Add thread to thread group                                                 Home

Thread Groups

Java provides a facility that user can group threads, and provide securities, priorities based on the group. There is only one root thread group, and a root thread group contains threads and other thread groups. Same applicable to other thread groups also, a thread group can contain other threads or other thread groups.


A Thread belongs to exactly one group. Thread Groups are similar to directories in System. Threads in the Thread group are similar to files in a directory. A directory can contain other directories and files, like that a Thread group can contain other thread groups and threads.

As we know, there is always a thread called main thread runs, whenever the main method called. The main thread by default in the thread group “main”.

Below is the toString() implementation for the Thread class. When a thread object is called in the print method, toString() is invoked by default.

public String toString() {
 ThreadGroup group = getThreadGroup();
 if (group != null) {
  return "Thread[" + getName() + "," + getPriority() + "," + group.getName() + "]";
 } 
 else {
  return "Thread[" + getName() + "," + getPriority() + "," + "" + "]";
 }
}

As you observe, it prints thread name followed by priority of the thread followed by Thread group name, if it exists.

class ThreadEx{
 public static void main(String args[]){
  System.out.println(Thread.currentThread());
 }
}
   
Output
Thread[main,5,main]

Thread[main,5,main] : "main" is the thread name
Thread[main,5,main] :5 is the priority of the thread
Thread[main,5,main] :"main" is the group name of the current thread.

Display active threads                                                 Create Thread Group                                                 Home

show all active threads: enumerate

public static int enumerate(Thread tarray[])
enumerate method copies all the active threads from the current threads threadgroup and its subgroups into an array.

public class EnumerateEx implements Runnable {
 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(InterruptedException e){
  }
 }

 public static void main(String args[]){
  EnumerateEx task1 = new EnumerateEx();
  EnumerateEx task2 = new EnumerateEx();
  EnumerateEx task3 = new EnumerateEx();

  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task2);
  Thread t3 = new Thread(task3);

  t1.start();
  t2.start();
  t3.start();

  int count = Thread.activeCount();
  Thread t[] = new Thread[count];
  Thread.enumerate(t);

  for(int i=0; i< t.length; i++){
   System.out.println(t[i]);
  }
 }
}
  
 Output
Thread[main,5,main]
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-2,5,main]

The implementation of enumerate looks like below

public static int enumerate(Thread tarray[]) {
     return currentThread().getThreadGroup().enumerate(tarray);
}





Active Threads Count                                                 Thread Groups                                                 Home

Monday, 3 March 2014

Active Threads Count: activeCount

public static int activeCount()
Returns the number of active threads in the current thread's thread group.

class ThreadCountEx implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
  }
 }

 public static void main(String args[])throws Exception{
  ThreadCountEx task1 = new ThreadCountEx();
  ThreadCountEx task2 = new ThreadCountEx();

  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task2);

  t1.start();
  t2.start();

  System.out.println("Active thread count is " + t1.activeCount());

  t1.join();
  t2.join();

  System.out.println("Active thread count is " + t1.activeCount());
 }
}
   
Output
Active thread count is 3
Active thread count is 1
    
As you observe the output, threads t1 and t2 are created in main thread, main thread is part of main thread group. So threads t1 and t2 also are part of main thread group. ActiveCount() returns 3 since 2 threads t1 and t2, main thread are active in the main thread group. Since activeCount() is static method, you can directly call it by using class name.


Get All Stack traces                                                 Display Active Threads                                                 Home

Get the state of a thread : getState()

public Thread.State getState()
Returns the state of this thread.

Example
class ThreadStateEx extends Thread{
 public void run(){
  try{
   Thread.currentThread().sleep(500);
  }
  catch(InterruptedException e){
  }
 }

 public static void main(String args[])throws Exception{
  ThreadStateEx t1 = new ThreadStateEx();
  ThreadStateEx t2 = new ThreadStateEx();
  ThreadStateEx t3 = new ThreadStateEx();

  t1.start();
  t2.start();
  t3.start();

  System.out.println("Thread1 state is " + t1.getState());
  System.out.println("Thread2 state is " + t2.getState());
  System.out.println("Thread3 state is " + t3.getState());

  t1.join();
  t2.join();
  t3.join();

  System.out.println("Thread1 state is " + t1.getState());
  System.out.println("Thread2 state is " + t2.getState());
  System.out.println("Thread3 state is " + t3.getState());
 }
}

Output   
Thread1 state is TIMED_WAITING
Thread2 state is TIMED_WAITING
Thread3 state is TIMED_WAITING
Thread1 state is TERMINATED
Thread2 state is TERMINATED
Thread3 state is TERMINATED


Thread State                                                 Wait & notify in Object class                                                 Home

Thread.State

Thread.State is of type enum and represents the states of a thread.

Below Example shows the different states of a thread in Java
   
class ThreadState{
 public static void main(String args[]){
  for(Thread.State c : Thread.State.values())
   System.out.println(c);
   }
}

Output
NEW
RUNNABLE
BLOCKED
WAITING
TIMED_WAITING
TERMINATED

State
Description
NEW
It is the state where thread is created and not yet started
RUNNABLE
A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.
BLOCKED
It is the state, where a thread is blocked to acquire a monitor lock
WAITING
A thread is in waiting state by calling wait() or join() methods with no time outs, I.e, with no parameters passing to them
TIMED_WAITING
A thread is in the timed waiting state due to calling one of the methods sleep, wait, join with a specified positive waiting time
TERMINATED
Thread completes execution or stopped.

Thread.state has two methods

1. public static Thread.State[] values()
Returns the array contains the all enum constants of this type.

2. public static Thread.State valueOf(String name)
Method returns the enum constant with the specified String.

Example
class ThreadState{
 public static void main(String args[]){
  Thread.State const1 = Thread.State.valueOf("NEW");
  Thread.State const2 = Thread.State.valueOf("RUNNABLE");
  Thread.State const3 = Thread.State.valueOf("TERMINATED");

  System.out.println("const1 is " + const1);
  System.out.println("const2 is " + const2);
  System.out.println("const3 is " + const3);
 }
}

Output
const1 is NEW
const2 is RUNNABLE
const3 is TERMINATED


   
Thread states                                                 Get Thread state                                                 Home