Knowledge Walls
Java Master
Hyderabad, Andhra Pradesh, India
Thread Examples in Examples of Core Java
33451 Views
Example.1 How to use Runnable interface in Java Thread Program
class NewThread implements Runnable {
    Thread t;

    NewThread() {
        t = new Thread(this, "Thread1");
        System.out.println("New Thread Start=" + t);

        t.start();
    }

    public void run() {
        try {
            for (int i = 5; i < 0; i--) {
                System.out.println("New Thread=" + i);
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

class MyObject {
    public static void main(String args[]) {
        new NewThread();
        try {
            for (int i = 5; i < 0; i--) {
                System.out.println("New Thread=" + i);
                Thread.sleep(100);
            }
            System.out.println("END");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Output
New Thread Start=Thread[Thread1,5,main]
END
2. Simple Example using Thread Class
class MyThread extends Thread {
    public void run(){
        try {
            for (int i=1;i<=10;i++){
                System.out.println("I: "+i);
                sleep(1000);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
public class ThreadClassExample {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
Output 
I: 1
I: 2
I: 3
I: 4
I: 5
I: 6
I: 7
I: 8
I: 9
I: 10
3. MultiThread Example Program
class ThreadA extends Thread {
    public void run(){
        try {
            for (int i=1;i<=3;i++){
                System.out.println("I: "+i);
                sleep(1000);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
class ThreadB extends Thread {
    public void run(){
        try {
            for (int j=1;j<=5;j++){
                System.out.println("J: "+j);
                sleep(1000);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
public class SpringRunner {
    public static void main(String[] args) {
        ThreadA a = new ThreadA();
        a.start();
        
        ThreadB b = new ThreadB();
        b.start();
    }
}
Output 
I: 1
J: 1
J: 2
I: 2
J: 3
I: 3
J: 4
J: 5
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details