Gangmax Blog

自由之思想,独立之精神

Some Java Concurrent Programming Hints

| Comments

  • 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:

1
2
3
4
5
6
7
8
try {
    while (!Thread.currentThread().isInterrupted()) {
    Thread.sleep(5000);
    System.out.println("Hello World!");
    }
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

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.

Comments