Home > Articles > Programming > User Interface (UI)

  • Print
  • + Share This
Like this article? We recommend

Multithreaded GUI Issues to Look Out For

So, it's really not too difficult making your code multithreaded. However, to avoid getting into difficulties, it's important to remember a few things about using threads. The first relates to the sharing of data. Imagine two threads—Thread A and Thread B—that each can modify an item of data. You have to be careful in this situation because there is no way of knowing when the two threads will execute. By electing to use threads, you are delegating to the operating system the problem of scheduling thread execution. So, if you share data between threads, you might inadvertently overwrite changes from the other thread. This can produce some very difficult debugging problems, so it's one to watch out for.

Another similar problem with threads is that of deadlock. This occurs when two or more threads share lockable resources. Imagine that Thread A and Thread B both use the same TCP port to send data to a server. Each thread waits its turn, opens the port, sends its data, and then closes the port. However, if one of the ports keeps the port open for some reason, then you have a deadlock, or a deadly embrace as it's sometimes known.

It's important to try to avoid these potential problems when you design multithreaded code. Techniques that can help include using the yield() method. Also, critical code sections can be protected using classes from the java.util.concurrent package.

Running the Supplied Java Code

To run the code, download it and unzip it into any old folder. Next, open a DOS console, change the directory to where the unzipped code files reside, and run the command javac *.java. To run the code, update your classpath as follows:

set CLASSPATH=.;%CLASSPATH%

To run the programs type:

java ThreadBareGui

You can the open another DOS console and repeat the setup steps above and then type:

java ThreadRichGui
  • + Share This
  • 🔖 Save To Your Account