JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java Thread By Extending Thread Class

  • A thread can be created in java by extending Thread class, where you must override run() method.
  • Call start() method to start executing the thread object.

Thread Sample Code

Code:
package com.myjava.threads;

class MySmpThread extends Thread{
    public static int myCount = 0;
    public void run(){
        while(MySmpThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MySmpThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    }
}
public class RunThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MySmpThread mst = new MySmpThread();
        mst.start();
        while(MySmpThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MySmpThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}

Example Output

Starting Main Thread...
Main Thread: 1
Expl Thread: 2
Expl Thread: 3
Main Thread: 4
Expl Thread: 5
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Main Thread: 8
Expl Thread: 9
Expl Thread: 11
Main Thread: 10
End of Main Thread...

Other Thread Examples

Knowledge Centre
What is daemon thread?
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
Famous Quotations
Tomorrow is often the busiest day of the week.
-- Spanish Proverb

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.