>

Saturday, December 15, 2012

Part Java I\O Part |||

In this post, I will try how to make program that java response from console, what in my concern is no matter you put any kind type data in console such char, string, and Number, we always use the same class InputStreamReader and BufferedReader, the differences is how we manipulate that data capture from console. I will start from from simple for char type.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CharacterInputDemo {

  public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
   System.out.println("Please Input Random Character : ");
    char character;
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader buffer = new BufferedReader(input);
     character = (char) buffer.read();
 
     System.out.println("Character \'"+character+"\'");
   }

}


as we see above our input was casting to char, because every time retrieve value from BufferedReader class the data type is integer, because we want in char type then we cast integer to char. Now I will show if we want capture string type from console ok, take look code bellow:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StringInputDemo {

public static void main(String[] args) throws IOException {
   System.out.println("what is your name ? ");
   String name;

   InputStreamReader input = new InputStreamReader(System.in);
   BufferedReader buffer = new BufferedReader(input);

   name = buffer.readLine();
   System.out.println("Hello, "+name+" nice too meet you !");
   }
}



as we see above we don’t have to casting from the input that we have put because BufferedReader class have method “readLine()” to capture from console and when we retrieve automatic in string form. Now I will show how to what if put number type like integer, check out the code bellow:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NumberInputDemo {
  public static void main(String[] args) throws IOException {
   
  String temp;
  int a = 0;
  System.out.println("Pick a number please ? ");

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader buffer = new BufferedReader(input);
  temp = buffer.readLine();

  try {
    a = Integer.parseInt(temp);
    System.out.println("the power 2 of your value "+a*a);

  }catch(NumberFormatException numberFormatException) {
  System.err.println("Data that you has put "+temp+"notnumber");
    }
  }
}
As we see above we capture value from console was same as we for string value, the difference is we convert to the format as we want and prevent if we put not in number form.

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.

Thread Part II - Stop the Thread and MultiThreading in java


Thread Part II
Stop the Thread and MultiThreading in java

Every thread that has been executed will be stop after every code in run() is finished executed, method will be automatic stop, but it doesn’t mean we can’t stop thread every time we want, we can stop thread using method stop(), but this method not recommended because the method is deprecated, the best thing that we can do by using boolean variable for controlling looping process.
Let’s see the example,

public class MyThreadStop extends Thread {
   private boolean finish = false;

   public void run() {
      int counter = 0;
      System.out.println("the child thread is executed...");

      while (!finish) {
        System.out.print((++counter) + " ");
       }
       System.out.println("the child thread is ended ");
      } 
// method as flag trigger to stop looping, once this method is
// invoke
   public void stopThread() {
    finish = true;
   }
}

No matter what in method run looping or not, as long as we give flag to stop the method run(), we can stop our thread as we see the code bellow

public class MyThreadStopDemo {

public static void main(String[]args)throws InterruptedException{
  
  System.out.println("the main thread is executed...");
  MyThreadStop myThreadStop = new MyThreadStop();
  myThreadStop.start();
  Thread.sleep(25);
 // triggering method to stop child thread
  myThreadStop.stopThread();
  System.out.println("\nEnd main Thread ");
  
  }

}


for code above we see that we didn’t called stop() method belong to the thread we just call a method stop contain a flag for stopping process in run() method.

in java program we need more than one child thread, program that contain thread more than one child thread called multithreaded. To prove java can handle multithreading we create two threads and invoke the two threads in demo class.

First thread :
public class MyThreadOne extends Thread{
   public void run(){
     try {
       for (int i = 0; i <10 ; i++) {
            System.out.println("First thread : "+(i+1));
            if( i!= 9){
               sleep(1000);
             }else{
              System.out.println("First thread finish....\n");
              }
            }
    }catch (InterruptedException e) {
      e.printStackTrace();
    }
   }
}

second thread :

public class MyThreadTwo extends Thread{
   public void run(){
     try {
       for (int i = 0; i < 5 ; i++) {
           System.out.println("Second thread :"+(i+1));
           if( i!= 4){
             sleep(1000);
             }else{
             System.out.println("Second thread finish....\n");
            }
           }
     } catch (InterruptedException e) {
       e.printStackTrace();
      }
    }
}

now we will call both thread
public class MutipleThreadDemo {

   public static void main(String[] args) {
    MyThreadOne myThreadOne = new MyThreadOne();
    myThreadOne.start();
    MyThreadTwo myThreadTwo = new MyThreadTwo();
    myThreadTwo.start();
   }
}


and if we execute demo class the result as shown bellow


First thread : 1
Second thread : 1
Second thread : 2
First thread : 2
First thread : 3
Second thread : 3
Second thread : 4
First thread : 4
First thread : 5
Second thread : 5
Second thread finish....

First thread : 6
First thread : 7
First thread : 8
First thread : 9
First thread : 10
First thread finish....

 
we see the result the first five line has same value it showed thread were executed together, after the sixth second running, second thread finished. Because only five looping steps for second thread. as the result above java has multithreading feature.

Thread Part III - Method isAlive and Join

Thread Part III
Method isAlive and Join

Sometime in our program we want our main thread be the last one to stop or finish, after all the child threads finished. For making this happen, firstly we need to check weather the child threads is alive using method isAlive(), then we use method join(), that belong to Thread Class. let’s check how it work first we create thread. As shown below,

public class MyThreadMain implements Runnable {

  private Thread thread;
  private int n;

  MyThreadMain(String name, int n){
   thread = new Thread(this, name);
   this.n = n;
  }

@Override
  public void run() {

  try {

    for (int i = 0; i <n; i++) {
System.out.println("Thread"+ thread.getName() +"second: "+(i+1));
  Thread.sleep(1000);
   }
System.out.println("Thread "+ thread.getName() +" finish.... ");
} catch (Exception e) {
   e.printStackTrace();
   }
}


   public void start(){
     thread.start();
   }

   public Thread getThread(){
     return thread;
   }
}

Now we try to make a few threads running together

public class IsAliveJoinDemo {

public stati cvoid main(String[]args)throws InterruptedException{
   System.out.println("\nMain Thread execute....");

   MyThreadMain t1 = new MyThreadMain("first", 2);
   MyThreadMain t2 = new MyThreadMain("second", 3);
   MyThreadMain t3 = new MyThreadMain("third", 3);

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

  System.out.println("t1 is alive ? "+ t1.getThread().isAlive());
  System.out.println("t2 is alive ?"+ t2.getThread().isAlive());
  System.out.println("t3 is alive ?"+ t3.getThread().isAlive());

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

  System.out.println("t1 is alive ? "+ t1.getThread().isAlive());
  System.out.println("t2 is alive ?"+ t2.getThread().isAlive());
  System.out.println("t3 is alive ?"+ t3.getThread().isAlive());

  System.out.println("\nMain Thread is executed..");
  }
}

if we run our code above the console will show below,

Main Thread execute....
t1 is alive ? true
Thread first second : 1
Thread second second : 1
Thread third second : 1
t2 is alive ?true
t3 is alive ?true
Thread third second : 2
Thread second second : 2
Thread first second : 2
Thread second second : 3
Thread third second : 3
Thread first finish....
Thread third finish....
Thread second finish....
t1 is alive ? false
t2 is alive ?false
t3 is alive ?false

Main Thread is executed..

as we saw for the result ,the main thread will be the last to finish after all the child threads is executed.

Thread Part IV - Determine Thread Priority in Java

Thread Part IV
Thread Priority

Thread Priority is set which thread to be priority to execute first, in theory the thread with the higher priority will be get more time CPU then the lower priority thread, the value of priority is MIN_PRIORITY to MAX_PRIORITY is 1 to 10 and for normal priority NORM_PRIORITY is 5. for determine priority in thread we use method setPriority() and to get the value priority we use method getPriority() both are belong to thread class. Ok let’s try how both method work, the idea was to figure how many looping created for high priority and low priority. First we created generated thread as shown bellow,

public class MyThreadPriority implements Runnable{

  private Thread thread;
  private long n;

  private boolean finish = false;

  MyThreadPriority(String name, int priority){
   thread = new Thread(this, name);
   thread.setPriority(priority);
  }

  @Override
  public void run() {
    while (!finish) {
     n++;
    }
  }

 public void start(){
  thread.start();
 }

 public void stop(){
  finish = true;
 }

 public long getN(){
  return n;
  }

 public Thread getThread(){
   return thread;
 }
}

 

then we try to create demonstration to check how priority work

public class PriorityThreadDemo {

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

  MyThreadPriority t1= new MyThreadPriority("high"
  Thread.NORM_PRIORITY+ 2);

  MyThreadPriority t2 = new MyThreadPriority("low"
  Thread.NORM_PRIORITY-2);

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

  Thread.sleep(5000);

  t1.stop();
  t2.stop();

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

  System.out.println("The number of looping for "+
  t1.getThread().getName()+" thread priority" +" : "+ t1.getN());

  System.out.println("The number of looping for "+
  t2.getThread().getName()+" thread priority" +" : "+ t2.getN());


  }
}

if we run the class above the console will show look like bellow,

The number of looping for high thread priority : 1351468823
The number of looping for low thread priority : 1301962925

from the result above the higher priority thread will do many looping than the lower one, and the value of looping above will be different for every CPU speed and how many applications running, but all will show the higher priority will do many looping than the lower one.