Threads Java Example

Threads Java Example

Previous Home Next

 

Threads Java Example

 

 // program for creating a simple thread
package r4r.co.in;

class MYThread implements Runnable {

    String name;                                     
    Thread t;

    MYThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("My thread: " + t);
        t.start();                                   // Thread Start for execution
    }

    synchronized public void run() {               // providing lock to the thread
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(name + ": " + i);
                Thread.sleep(100);
            }
        } catch (Exception e) {
            System.out.println(name + e);
        }
        System.out.println(name + " exiting.");
    }
}

class ThreadDemo {

    public static void main(String args[]) {
        new MYThread("One");                // name of thread
    }
}

My thread: Thread[One,5,main]
One: 0
One: 1
One: 2
One: 3
One: 4
One: 5
One: 6
One: 7
One: 8
One: 9
One exiting.
Previous Home Next