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

package com.myjava.threads;

class MySmpThread extends Thread{
    public static int myCount = 0;
    public void run(){
        while(MySmpThread.myCount <= 10){
                System.out.println("Expl Thread: "+(++MySmpThread.myCount));
            } 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();
        while(MySmpThread.myCount <= 10){
                System.out.println("Main Thread: "+(++MySmpThread.myCount));
            } 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
Interface and its usage
Interface is similar to a class which may contain method's signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for declaring methods that one or more classes are expected to implement, capturing similarities between unrelated classes without forcing a class relationship and determining an object's programming interface without revealing the actual body of the class.
Famous Quotations
We know what we are, but know not what we may be.
-- William Shakespeare

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 © 2018 by Nataraja Gootooru. All Rights Reserved.