- The right “join” usage(from here)
Start all the threads first, then “join” all of them. I made it wrong by joining a thread right after starting it inside a for loop of several threads. This wrong usage will start the first thread only.
- Be careful to add “synchronized” to methods of a class which may cause dead lock
The base idea is that, when a “synchronized” instance method is invoked, the instance is locked by that thread. During that running period, if another thread invokes another “synchronized” method of this instance, it will wait until it gets the instance lock. In my case, I add “synchronized” to both of the “start()” and the “stop()” methods of a class. However, the “stop()” method invoked by the worker thread will not work because it can never get the lock ocuppied by the main thread which invoked the “start()” method, since the “start” method starts the worker threads.
- The right way to interrupt a sleeping thread(from here)
The code is:
The key point is to use “isInterrupted()” method to check before sleeping. My wrong code used “while(true)” which will cause the InterruptedException to be thrown when trying to interrupt the thread.