Running Code in a Different Thread


You need to write a threaded application.


Write code that implements Runnable; instantiate and start it.


There are two ways to implement threading, and both require you to implement the Runnable interface. Runnable has only one method, whose signature is:

public void run(  );

You must provide an implementation of the run() method. When this method returns, the thread is used up and can never be restarted or reused. Note that there is nothing special in the compiled class file about this method; it’s an ordinary method and you could call it yourself. But then what? There wouldn’t be the special magic that launches it as an independent flow of control, so it wouldn’t run concurrently with your main program or flow of control. For this, you need to invoke the magic of thread creation.

One way to do this is simply to subclass from java.lang.Thread (which also implements this interface; you do not need to declare redundantly that you implement it). This approach is shown in Example 24-1. Class ThreadsDemo simply prints a series of Xs and Ys; the order in which they appear is indeterminate, since there is nothing in either Java or the program to determine the order of things.

Example 24-1.

/** * Threaded demo application, as a Threads subclass. */ public class ThreadsDemo1 extends Thread { String mesg; int count; /** Run does the work: print a message, "count" number of times */ public void run( ) { while (count-- ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.