Tuesday, August 20, 2013

Multi-threading: For my sophomore



Yash: Today I have learned about Multi-threading in Java.

Me: Excellent. Explain to me.

Yash: I can explain it as a game.

Me: Wow!!

Yash: It is very easy. Let us assume that I have four of my friends are at home.  Each one has one marker and an eraser. There is also one small size white board in the room.  In this game each person is supposed to write his name at white board. But board is so small that only one name can fit in at a given point of time. Now let us begin the game.

In the start of game each person is asked to write his name on the board. Now everyone tries to write his name on board. Since board can hold only one name, so it is possible that nobody able to write his name on the board. Ouch!! It is mess.

Now let us change rules little bit. Now you pitch in seeing the mess and set one more rule. Rule is: Any one can write his name on the board if he has token provided by you.

Now game starts again. This time boys have raced to get token from you not at white board. One who gets the token gets a chance to write his name on the board.  This means at a given point of time only one person is working on board.

Here you can replace boys with threads, white board with object of piece of code on which multiple threads want to operate, token with monitor.

This is how multi-threading is implemented in Java.

Me: Superb…

No comments:

Post a Comment