Thursday, June 07, 2012

Java Threads for Hello World

//Extends Threads class DispThread extends Thread {
String msg;

    public void run() {
    try {
    for(int i = 2; i > 0; i--) {  //delay
    System.out.println("Child Thread: " + i);
    Thread.sleep(10000);
    }
    } catch (InterruptedException e) {
        System.out.println("Child interrupted.");
    }
      
        System.out.println("Exiting child thread." + msg);
    }
    public DispThread(String m){
        msg = m;
    }
}
class ThreadTest {
    public static void main(String args[]) {
   
      DispThread dt1 = new DispThread("Hello");
      DispThread dt2 = new DispThread("World");
      dt1.start();  // call user thread from main thread
      dt2.start();
   
    }
}
With the delay the output
Running tool: javac

javac ThreadTest.java
java ThreadTest
Child Thread: 2
Child Thread: 2
Child Thread: 1
Child Thread: 1
Exiting child thread.Hello
Exiting child thread.World

Done.

//Implements Runnable
class DispThread implements Runnable {
String msg;

    public void run() {
    try {
   for(int i = 5; i > 0; i--) {  //delay or sleep
    System.out.println("Child Thread: " + i);
    Thread.sleep(500);
     }
    } catch (InterruptedException e) {
       System.out.println("Child interrupted.");
      }
        System.out.println("Exiting child thread." + msg);
    }
    public DispThread(String m){
        msg = m;
    }
}

class ThreadTest1 {
    public static void main(String args[]) {
   
      DispThread dt1 = new DispThread("Hello");
      DispThread dt2 = new DispThread("World");
      Thread t1 = new Thread(dt1);   //because implements need to create an object
      Thread t2 = new Thread(dt2);
      t1.start();
      t2.start();
   
    }
}
//Without delay the output
Running tool: javac

javac ThreadTest1.java
java ThreadTest1
Exiting child thread.World
Exiting child thread.Hello

Done.

//No Thread just println
public class Hi {
public static void main(String argv[]){
   System.out.println("Hello World");
   }
}
javac Hi
Hello World

Done.

No comments: