Multi-threading in Java using Runnable interface: Part 1

× "Is a" and "Has a" relation "Has a" relation Arrays as in memory Two Dimensional Arrays Exception Handling Variable, Object & Reference Multi-threading Website Design / Development Story of JEE modules
× JAVA, JEE, SQL: Online Private Tutoring Project based Training Concept based Training Basic Java:           $180 Advanced Java:     $300
(Threads,Sockets,JDBC,GUI)
Advanced Java:     $300
(with games projects like
PcMan, PingPong, TicTacToe)
Author: Bharat Chhajer

Create source In here, we create two classes in a package called thread.runnable:
  NumberPrinter.java and
  MyApp.java

Following is the directory structure
  C:\..\thread_examples\src (folder containing source files)
  C:\....\thread_examples\bin (folder containing compiled classes)

Following is the source for NumberPrinter.java
package thread.runnable;
public class NumberPrinter implements Runnable {
  public void run() {
   for(int i=0; i<15; i++){
    System.out.println("NumberPrinterThread: " + i);
    Thread.yield();
   }
  }
}

Note that there is a difference between NumberPrinter and NumberPrinterThread class in the previous example. NumberPrinter implements a Runnable Interface. Thread.yield() makes the main thread yield the processing resources to the JVM. One of the active threads now get a chance to execute its line of code.

Following is the source for MyApp.java
package thread.runnable;
public class MyApp {
  public static void main(String[] args) {
   Thread thread = new Thread( new NumberPrinter());
   thread.start();
   for(int i=0; i<15; i++){
    System.out.println("Main Thread: " + i);
    Thread.yield();
   }
  }
}


Author: Bharat Chhajer