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
StringBuffer Vs StringBuilder
The only difference between StringBuffer and StringBuilder is StringBuffer is thread-safe, that is StringBuffer is synchronized.
Famous Quotations
I don’t know the key to success, but the key to failure is trying to please everybody.
-- Bill Cosby

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.