Thinking in Threads - 1
[Read this article]
Thinking in Threads is a profitable endeavor, if at all you need a reason.
Thread is a remarkable abstraction of parallel processing. By training ourselves
to use threads properly, we prepare ourselves for the inevitable future boom
of parallel processing. What Modularity is for Complexity, Parallelism is for
Utilization.
First, what is thread after all? If you consider a top-down program as a flowchart,
a thread is just one flowchart, or flow of statements. Multiple threads are just
multiple flows. If we already know how to code one flow, we also know to code one
hundred of it, if need be. In fact Java makes this flow idea obvious, by
abstracting a thread to an interface
Runnable
which just
contain one method, run() . So, programming with threads is
after all, programming multiple programs together, or allowing many instance of
a given program to run together. What spoils this beautiful picture? The
need for communication between threads.
Thinking in Threads - 2
[Read this article]
...this new primitive is far less safe than using the
synchronized keyword. Why? Because, if we omit the closing call to
allow , the thread sleeps for ever. Java being a highly type safe
language, tries to increase the opportunities for the compiler to check for
these types of human mistakes. By using a synchronized block,
provided by the language itself, the code is structured and hence is safe.
This idea is just like say, the while loop. Before it was invented,
people used goto to simulate that, with the potential danger of
missing the goto , or pointing it to some improper places. By including
loops as a basic construct of the language itself, these common mistakes
are now compile time checked, and hence are safe.
|