Sunday, March 6, 2011

Java Multithreading

I know this is one of the most basic topic that even second year university should be familiar with, however, this afternoon I have spent nearly a whole afternoon to debug some issues with Java Multi-threading, and only at that point I realized I am far far away from fully understanding the seemingly easy problem.

As I have reading through all kinds of tutorials, discussions available, I believe the best way would be to sommarize what I have found and record it as my own writing.

So here is the beginning, Java always running with a single thread if there is no request for a new thread to be spawned. However, in some circumstances, a separate thread is needed to perform some other tasks either to be parallel with the main thread or as a background job. There are two ways to achieve multi-thread in Java, as everyone should be familiar with: implements Runnable and extends Thread.

Basically, most of the time, implements Runnable should be the preference over extends Thread, unless you need to specifically override the life cycle method of the thread (which is rare). These two ways do nearly the same thing except when you subclass Thread, you are trapped in the spot that no other class can inherit as Java only allows single inheritance. While if you implements the interface, you still have the ability to extend any class you wish.

Next, let's go into the main method in the body -- run(). Actually, you have the choice to call run() and start() to execute the body. However, there is some slight differences between these two methods. run() will execute the method immediately in the current thread, and start() will spawn a new thread and the execution will be invoked undeterministicallly. As a rule of thumb, we should avoid to use run() but use start() all the time. The reason we have a multi-thread class is to run it in a separate thread. If we just call the run(), everything will run sequentially as there is no thread existed. run() should always invoked by JVM not the application.

Another point we should pay some attention is Executor which comes from JDK 5. Instead of explicitly calling new MyThread().start() to invoke the new thread, Executor can decouple the task submission from the real method perform -> executor.execute(new MyThread()).

No comments:

Post a Comment