Creating thread using Thread Class: 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 two classes in a package called thread.thread:
     NumberPrinterThread.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 NumberPrinterThread.java

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

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

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.


Author: Bharat Chhajer