>

Saturday, December 15, 2012

Thread Part I -Main Thread, Child thread and Method for Creating Thread

 Thread Part I
Main Thread, Child thread and Method for Creating Thread

Thread is part of program which is independent and can be run simultaneous, it mean a thread can be paused without to stop whole program. Every thread in java is inheritance from thread class in package java.lang. When we run java program in our program there will be at least one thread, this thread named main thread and the other thread named child thread .Let’s see how there is at least one thread in every time we run java program.

Here the full code :

public class MainThreadDemo {

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

  // retrieve the active thread
     Thread mainThread = Thread.currentThread();
     System.out.println("the default thread name :");
     System.out.println(mainThread.toString());
   // changing default thread name
     mainThread.setName("Main Thread");
     System.out.println("retrieve the new name for thread :");
     System.out.println(mainThread.toString());
     System.out.println("example for controlling thread");
     for (int i = 0; i < 5; i++) {
       System.out.println("delay..."+(i+1));
       Thread.sleep(1000);
     }
   }
}



the output when retrieving the default thread name
Thread[main,5,main] → [thread name, priority, group]
as how above that is the out format when we try current thread, main was the name of thread, the thread priority value is 5 and the group name is main.

For creating thread or child thread there are two method, first using interface and implements to the class that we made for thread,

public class MyRunnable implements Runnable{
@Override
   public void run() {
    System.out.println("the child thread is executed...");
   }
}


for running thread show bellow

public class MyRunnableDemo {
  public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    Thread thread = new Thread(myRunnable);
    thread.start();
    System.out.println("the main thread is executed...");
   }
}

if we run the result show bellow,

the main thread is executed...
the child thread is executed...

both method for running the thread we must call method start from thread itself, then automatic call run method for thread. We saw that the output both thread show that the program will execute main thread first and then the child thread.

Perhaps we confuse which one we should use, its depend on what you need, if we see in design side using interface is the best one, and also it is fit, if we just need runnable method only without override the from thread class, but if you need to modify every method in thread class extends thread class is the best way.

No comments:

Post a Comment