27 June 2013

Simple Thread Example in Java

This is a simple Thread example. I am utilizing Runnable interface to create Threads. In the main method it generates 5 threads, and start them. Each thread print out the simpleName set in the main method. Running this code, you will get basic idea of how threads are working.


Text version:

/**
 * Created with IntelliJ IDEA.
 * User: shahin
 * Date: 6/5/13
 * Time: 11:32 PM
 * To change this template use File | Settings | File Templates.
 */
public class SimpleThread implements Runnable{

    public SimpleThread(String simpleName) {
        this.simpleName = simpleName;
        System.out.println(">>> Constructor for " + getSimpleName());
    }

    public String getSimpleName() {
        return simpleName;
    }

    public void setSimpleName(String simpleName) {
        this.simpleName = simpleName;
    }

    private String simpleName;
    @Override
    public void run() {
        System.out.println(" >> "+getSimpleName() + " started.");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        System.out.println(" >> "+getSimpleName() + " stopped.");
    }

    public static void main(String args[])
    {
        System.out.println("Main Thread started.");

        SimpleWaitNotifyThread simpleThread;
        Thread thread;
        for(int i=0;i<5;i++)
        {
            simpleThread = new SimpleWaitNotifyThread("Thread "+(i+1));
            thread = new Thread(simpleThread,"Thread "+(i+1));
            thread.start();
        }

        System.out.println("Main Thread finished.");
    }
}

No comments:

Post a Comment