Simple MultiThreading


I wrote this small program to implement Java’s MultiThreading capabilities. This is the bare minimum that you can do with it. Its extremely powerful and useful and reasonably easy to use. This program is for beginners who cant understand what multi-threading is all about. The program is self-explanatory. As always, for any clarifications or doubts leave a comment below!

import java.util.Scanner;

/**
*A Simple Java program to explain basic MultiThreading.
*@authorSteve Robinson
*@see footyntech.wordpress.com
*/

class ThreadTest implements Runnable
{
    public int buffer=0;
    public void run()
    {
        try
        {
            for(int i=0;i<50;i++)
            {
                buffer+=i;
                Thread.sleep(400);
            }
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("Child Thread Ended");
    }
}

class MultiThreading
{
    public static void main(String arg[])
    {
        ThreadTest temp=new ThreadTest();
        Runnable r=temp;

        Thread thread=new Thread(r);
        thread.start();

        String in;
        Scanner input=new Scanner(System.in);

        System.out.println("Press \"p\" to print current value and \"q\" to quit");
        while(!((in=input.nextLine()).equals("q")))
        {
            if(in.equals("p"))
            {
                    System.out.println("Current Value: " + temp.buffer);
            }
        }
        System.out.println("Stopping Child Thread....\nExiting....");

        //Deprecated method. Please ignore warnings...
        thread.stop();  

    }
}

Complete Source Code:

Pastebin Paste

Steve Robinson

One thought on “Simple MultiThreading

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s