Concurrency improvements

The ability to employ multiple threads in our Java applications stands to greatly improve efficiency and leverages the increasing processing capabilities of modern computers. The use of threads in Java gives us great granularity in our concurrency controls.

Threads are at the core of Java's concurrency functionality. We can create a thread in Java by defining a run method and instantiating a Thread object. There are two methods of accomplishing this set of tasks. Our first option is to extend the Thread class and override the Thread.run() method. Here is an example of that approach:

. . .
class PacktThread extends Thread {
. . .
public void run() {
. . .
}
}
. . .
Thread varT = new PacktThread();
. . .
// This next line is start the Thread by
// executing the run() method.
varT.start();
. . .

A second approach is to create a class that implements the Runnable interface and pass an instance of the class to the constructor of Thread. Here is an example:

. . .
class PacktRunner implements Runnable {
. . .
public void run() {
. . .
}
}
. . .
PacktRunner varR = new PacktRunner();
Thread varT = new Thread(varR);
. . .
// This next line is start the Thread by
// executing the run() method.
varT.start();
. . .

Both of these methods work equally well, and which one you use is considered to be the developer's choice. Of course, if you are looking for additional flexibility, the second approach is probably a better one to use. You can experiment with both methods to help you make a decision.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset