Friday, May 25, 2012

1.1 Threads and Multithreading

This chapter and the subsequent ones on Threads and Multi-threading is probably by far the most complex topic we will be covering as part of our aim at getting a SCJP Certification.
Before we begin – let me put out a Disclaimer…


Disclaimer: This chapter makes almost no attempt to teach you how to design a good, safe, multithreaded application. The concepts covered in this article are just the tip of the iceberg and you’re here only to learn the basics of threading, and what you need to get through the thread questions on the exam. Before you can write decent multithreaded code, however, you really need to study more on the complexities and subtleties of multithreaded code.

In a single-threaded runtime environment, actions execute one after another. The next action can happen only when the previous one is finished. If task A takes half an hour, and the user wants to do something else, he is doomed to wait until task A is over.

Ideally, the user should be able to carry on with his other task until his first task is complete. Imagine having to wait till your eclipse build all your source code before you could check your email? Thankfully windows uses multiple threads to run your eclipse and outlook. So you don't have to go through this pain. Similarly java has options wherein the programmer can have multiple threads of execution running.

Now you are ready to dive into the magical or rather complicated world of threads.

Lets get started!!!

What is a Thread?

In Java, “thread” means:
• A thread of execution

A thread of execution is an individual process that has its own call stack. In Java, there is one thread per call stack or, to think of it in reverse, one call stack per thread. Even if you don’t create any new threads in your program, threads are there running without your knowledge.
If you are curious and ask me how? Just stop for a moment and think how you would execute a java program? You’ll write a main method and then execute it from the command line using the “java” command. Well, you have already answered the question because, when your main method starts, the JVM assigns a thread for this main method and assigns it a call stack. So, eventhough you did not intentionally create a thread, the system did one for you.

The most important concept to understand from this entire chapter is this:

When it comes to threads, very little is guaranteed.

So be very cautious about interpreting the behavior you see on one machine as “the way threads work.” The exam expects you to know what is and is not guaranteed behavior, so that you can design your program in such a way that it will work regardless of the underlying JVM.

NEXT

No comments:

Post a Comment

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...