The Java Multi Threading - basic concepts of thread model in java


Want to create an application which runs multiple functionality simultaniously? So now it is turn to learn threading with java. create multiple thread and do stuff like animation or multi processing with them.

The Concept of multi threading born from concurrent programming. Every Computer user uses so many applications at once so it was necessary for the software developers to provide some solution by which they could run multiple application simultaneously. This was obtain by using the concurrency. The application uses two trends Process based or thread based concurrency.

The Java Thread model

The Java thread model is based on the multi threading concept. The process is rather a big picture of an application but the thread is a smaller part. there could be more than one thread in a process. The Java Thread model treats everything as a thread. It is in the language specification of Java. When you run a Java program it creates a thread which is parent thread of all other threads in Java.

If you have made a guess, yes it is main method. It is the parent thread of all the threads. See the example as following program.


public class ThreadingDemo {
    public static void main(String[] args){
        System.out.println(Thread.currentThread());
    }
}
Thread[main,5,main]

This tells you which is current thread, the format is Thread[thread-name,thread-priority,thread-type]. If you want to try some changes in it. See to following program.


public class ThreadingDemo {
    public static void main(String[] args){
        Thread.currentThread().setPriority(7);
        Thread.currentThread().setName("test");
        System.out.println(Thread.currentThread());
    }
}
Thread[test,7,main]

Now you see the name and priority has been changed.

So this was a basic thread model. But What if you want to make your own thread ?

Yeah that is easy and now I am going to tell you that. But wait, Wouldn't you like to know why you would like to create threads if JVM is already taking care of this.

Yes, JVM is creating threads for you but what if you want to create a game in which you want to run a character and the background, on the same time enemies and their fires. Yes, here Java threads will help you. Or if consider you are making an audio video application. There you will need to run video and audio function simultaneously. There again you'll need multiple threads. Don't worry its not too difficult and we'll also give you a sample animation to work on after we finish up with all the concepts of Threading. So lets now move on.

Creating Threads In Java

There are two ways you can create Thread, One by using Thread class as super class. And secondly by implementing the interface Runnable. Following two programming example will tell you how.


public class ThreadingDemo extends Thread{
    
    public void run(){
        System.out.println("yey!! My New Thread is running.");
    }
    public static void main(String[] args){
        new ThreadingDemo().start();
    }
}

yey!! My New Thread is running.

Now did you noticed I called a start() method while I created a run method ?
Don't get confused. The Thread class comes with several method run() and start() are one of them. you start a thread by calling start() method on its object, which in this case is ThreadingDemo class object. You can call it on only the Thread type object but as ThreadingDemo is extending the Thread so here the inheritance principles comes into play.

When you call a start on the Thread, it executes the run() method. The run method is not created in ThreadingDemo but is Thread class method which is being overridden by the ThreadingDemo. Whatever function you want your thread to perform, you define it all in the run() method.

Now let us see another way for creating thread, that is implementing Runnable interface. Before we move on, let me tell you the reason why you will be following this method rather than extending thread.

Consider you are working on some program and you have a class hierarchy already defined for Inheritance purpose but now you need to create a Thread in your subclass. But wait, Java does not allow to extend multiple classes, what do we do then ?

If there is a problem, there is also a solution. The Runnable interface to the rescue. You can implement as many interfaces as you want. So you get a solution. To see how, please take a good look at following program.


public class ThreadingDemo implements Runnable{
    private Thread th;
    public void startThread(){
        th = new Thread(this);
        th.start();
    }
    
    public void run(){
        System.out.println("yey!! My New Thread is running.");
    }
    
    public static void main(String[] args){
        ThreadingDemo td = new ThreadingDemo();
        td.startThread();
    }
}

yey!! My New Thread is running.

Well, you see, it works. And is a good way to do the thing. The creation of thread object and starting it could have been more direct but I like to keep things proper and understandable. If you want just do it in constructor or however you want, I just wanted to make you understand the concept.

The run method in the program is now the only method provided with the Runnable Interface. The purpose is to make you able to create thread without the need for extending Thread class.

Thread Scheduling

The threads if you know by the means of their role in Operating system are part of system process. Every program want its own process to be executed first but it is up to CPU to help these processes and thread to work in concurrence. So Java also provide the utility method with the Thread class which allows you to do thread scheduling manually.

The sleep() method from the Thread class is used for the purpose. This method put your thread to sleep and allows another thread to execute*. Please look at following program to know the scenario.


public class ThreadingDemo implements Runnable{
    private Thread th;
    public void startThread(){
        th = new Thread(this);
        th.start();
    }
    
    public void run(){
        for(int i=0; i<5; i++){
            try{
                System.out.println(i);
                th.sleep(1000);
                
            }
            catch(InterruptedException ie){
                System.out.println(ie);
            }
        }
    }
    
    public static void main(String[] args){
        ThreadingDemo td = new ThreadingDemo();
        td.startThread();
        System.out.println("thread started");
    }
}

thread started
0
1
2
3
4

The thread now uses the sleep() method with 1000 millisecond as the argument. The argument passed in sleep() method is of type long. This throws InterruptedException so it is necessary to keep it inside try and catch block. This is one of the checked exception so if you don't do so, you'll get a warning from compiler.

Now when I run the program it produces the output, and you'll see that there is time delay of about a second in the successive printing of numbers in for loop. So this is how java allows you to take care of scheduling of your thread.

*Note: Please note that, JVM is also a system program running on the CPU so actually scheduling is handled by your CPU only. JVM acts as secondary Controller for the Java threads. So don't expect your program to run with the highest priority if you are setting the thread priority to the topmost**.

** Java defines priority from 1 to 10, which is also defined with constants, MIN_PRIORITY(1), NORM_PRIORITY(5) and MAX_PRIORITY(10). you can set the priority of thread using method setPriority().

There are more advance concept in the Java multi threading. I suggest practicing the basics first and than move on to Java Thread - Advance level multi Threading.