Running Code in a Different Thread

Problem

You need to write a threaded application.

Solution

Write code that implements Runnable; instantiate and start it.

Discussion

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. ThreadsDemo1.java

/** * 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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.