Creating Multi-threaded Applications with the Runnable Interface in Java

Printer Code 39 Full ASCII in Java Creating Multi-threaded Applications with the Runnable Interface
722 Creating Multi-threaded Applications with the Runnable Interface
Code39 Creation In Java
Using Barcode encoder for Java Control to generate, create Code 3 of 9 image in Java applications.
While extending the Thread class is one way to create a multi-threaded application, it isn't always the best way Remember, Java supports only single inheritance, unlike languages such as C++, which supports multiple inheritance This means that if a class extends the javalangThread class, it cannot extend any other class a feature that is often necessary in the design of Java software A better way is often to implement the javalangRunnable interface The Runnable interface defines a single method, run(), that must be implemented Classes implement this interface to show that they are capable of being run as a separate thread of execution The precise signature for the run method is as follows:
Printing Barcode In Java
Using Barcode generation for Java Control to generate, create bar code image in Java applications.
public void run ()
Recognizing Bar Code In Java
Using Barcode scanner for Java Control to read, scan read, scan image in Java applications.
The Runnable interface doesn't define any other methods, or provide any thread-specific functionality Its sole purpose is to identify classes capable of running as threads When an object implementing the Runnable interface is passed to the constructor of a thread, and the thread's start() method is invoked, the run() method will be called by the newly created thread When the run() method terminates, the thread stops executing There are several advantages to using the Runnable interface over extending the Thread class The first, as mentioned above, is that an object is free to inherit from a different class Second, the same Runnable object can be passed to more than one thread, so several concurrent threads can be using the same code and acting on the same data Though this use is not always advised, it can make sense in certain circumstances, providing that due care is taken to prevent conflicts over data access Third, carefully designed applications can minimize overhead, as creating a new Thread instance requires valuable memory and CPU time A Runnable instance, on the other hand, doesn't incur the same burden of a thread, and can still be passed to a thread at a later point in time to be reused and run again if necessary Below is an example of a multi-threaded application that uses the Runnable interface rather than a subclass of the Thread class
Generating Code 39 Full ASCII In Visual C#.NET
Using Barcode creator for .NET Control to generate, create Code 3 of 9 image in VS .NET applications.
// 7, Listing 2 public class RunnableThreadDemo implements javalangRunnable { // Run method is executed when thread first started public void run() { Systemoutprintln ("I am an instance of the javalangRunnable interface"); } // Main method to create and start threads public static void main(String args[]) { Systemoutprintln ("Creating runnable object"); // Create runnable object Runnable run = new RunnableThreadDemo(); // Create a thread, and pass the runnable object Systemoutprintln ("Creating first thread"); Thread t1 = new Thread (run); // Create a second thread, and pass the runnable object Systemoutprintln ("Creating second thread"); Thread t2 = new Thread (run); // Start both threads Systemoutprintln ("Starting both threads"); t1start(); t2start(); } }
Encode Code39 In .NET
Using Barcode creation for ASP.NET Control to generate, create Code 39 Full ASCII image in ASP.NET applications.
When the example is compiled and run, two threads can be seen printing a message to the console What is very different about this program, and the previous one, is that only one Runnable object was created, but two different threads ran it Although there was no shared data in this example, in more complex systems, threads must share access to resources, to prevent modification while a resource is being accessed This is achieved by synchronizing access to resources (discussed later in the chapter)
Print Code 39 In .NET
Using Barcode maker for VS .NET Control to generate, create Code 3 of 9 image in .NET applications.
723 Controlling Threads
Code 3/9 Generator In Visual Basic .NET
Using Barcode generator for .NET Control to generate, create Code 39 Extended image in VS .NET applications.
As shown in the previous two examples, it is relatively easy to start a thread executing There are other ways, too, of controlling threads 7231 Interrupting a Thread Observant readers may have noticed that whenever a call to the Thread sleep (int) method was made in earlier examples, an exception handler was used This is because the sleep method puts a thread to sleep for a long period of time, during which it is generally unable to rouse itself However, if a thread must be awakened earlier, interrupting a thread will awaken it; this is achieved by invoking the interrupt() method Of course, this requires another thread to maintain a reference to the sleeping thread The following example demonstrates the interruption of a thread, by using the Threadinterrupt() method:
Code-39 Maker In Java
Using Barcode drawer for Java Control to generate, create USS Code 39 image in Java applications.
// 7, Listing 3 public class SleepyHead extends Thread {
Generate UPC A In Java
Using Barcode generation for Java Control to generate, create UPC Symbol image in Java applications.
// Run method is executed when thread first started public void run() { Systemoutprintln ("I feel sleepy Wake me in eight hours"); try { // Sleep for eight hours Threadsleep( 1000 * 60 * 60 * 8 ); Systemoutprintln ("That was a nice nap"); } catch (InterruptedException ie) { Systemerrprintln ("Just five more minutes"); } } // Main method to create and start threads public static void main(String args[]) throws javaioIOException { // Create a 'sleepy' thread Thread sleepy = new SleepyHead(); // Start thread sleeping sleepystart(); // Prompt user and wait for input Systemoutprintln ("Press enter to interrupt the thread"); Systeminread(); // Interrupt the thread sleepyinterrupt(); } }
Printing Bar Code In Java
Using Barcode drawer for Java Control to generate, create bar code image in Java applications.
The sole purpose of the thread in this example is to go to sleep for a very long time Once the thread is sleeping, it cannot awaken itself The only course of action is to send an interrupt message from another thread Run the example, and you'll see that the thread is idle The primary thread (executing the main method) waits for the user to hit "enter," then sends an interrupt message (which will be caught unless the sleeping thread has awoken of its own accord and terminated) The secondary thread awakens, displays a message, and then terminates, allowing the application to close 7232 Stopping a Thread Sometimes it is necessary to terminate a thread before its task has been completed For example, if a network client is sending messages to a mail server in a second thread, and the user wants to cancel the operation (perhaps to delete a hastily constructed flame before it is sent), the thread should be stopped immediately One thread can send a stop message to another thread, by invoking the Threadstop() method This requires the controlling thread (issuing the stop message) to maintain a reference to the thread that it wants to shut down The following example demonstrates the use of the stop() method:
Painting Barcode In Java
Using Barcode drawer for Java Control to generate, create bar code image in Java applications.
Create EAN-13 Supplement 5 In Java
Using Barcode drawer for Java Control to generate, create UPC - 13 image in Java applications.
Draw ANSI/AIM Code 39 In .NET
Using Barcode creator for ASP.NET Control to generate, create Code 3 of 9 image in ASP.NET applications.
Printing GTIN - 13 In Visual Studio .NET
Using Barcode creation for .NET Control to generate, create EAN13 image in .NET framework applications.
ECC200 Encoder In Visual Basic .NET
Using Barcode generation for .NET Control to generate, create Data Matrix ECC200 image in .NET framework applications.
UPC - 13 Printer In Visual Studio .NET
Using Barcode generation for ASP.NET Control to generate, create EAN 13 image in ASP.NET applications.