Sunday, July 14, 2013

Thread

Sometimes a new bee in Java Programming can think why Thread is necessary, while our program can run in a single straight line flow? But have you ever think that if you are a game developer developing a game like magic bricks.
Here you need to do three or more things simultaneously (Maybe independent or dependent with each other) Like:
  1. Moving ball through the screen as it’s on speed and direction and bouncing back accordingly.
  2. Moving the slide on key board event as per user playing style.
  3. Destroying the bricks or playing some animation when ball is hitting on it.


But if you try those things without multi Thread, achieving those goals will be very critical.  That’s why multi threading is necessary. In our modern computing environment Thread is everywhere. Nowadays without multi thread we can’t imagine a single software, we application, game.
Moreover, If you have good grip on thread then you will have good grip on Java as well. Are you preparing for Java interview? Then also this article will help you a lot.
So take a cup of coffee and let’s start.

Suppose you have two computing task
1. Add through 1 to 10
2. Multiply through 1 to 10
 
Here is a simple program without thread.

Here is the following program sequence flow line.

But if we want to do those two tasks simultaneously, we will use Thread as follows.  Separate two task in two run method inside of two Thread class (Basically sub class of Thread) .






















Now change the main method. Instantiate both class and start the thread using start() method  as follows.









Here is the output. Try that program on your own hand for better understanding.
 

No comments:

Post a Comment