|
|
||
|
Welcome to RoadDust's Java thread tutorial. Here you will learn how to create a simple thread. As you will see in this Java tutorial, it is very easy to use a thread in Java. Java Thread Creation and usage.How to create a thread in Java.The following code example shows you how to create a thread with Java. This is the entire code taken from a small Java Applet that zooms into an image. I will now walk you through the above Java Thread code example step by step. The first thing you must do is modify your class definition to implement "Runnable", this is necessary if you wish to use a thread. Simply modify your class definition by adding "implements Runnable" as seen in the following example. The next step is to declare your thread, you can do so by using the following syntax. You must now create the start method which will trigger automatically when your application runs. In this start method you will initialize your thread and begin its execution. Here is the syntax for the start method. Since you have a start method you should also have a stop method to end the execution of your thread. The following example demonstrates the stop method in which the thread is set back to "null". Finally, you have the run method which contains the code that your thread will be running. In this example you will see that it runs a "do while" loop that ends when the boolean "keepGoing" is set to false. In the above example you will see the command "Thread.sleep(50);". This command stops the execution of the thread for 50 milliseconds (1000 for every second). This command must be put in a "try/catch" statement because it will generate an exception. If you do not put it in a "try/catch" statement you will get an error when you attempt to compile. You will also see in the example above that I increment some variables and then call the "repaint()" function. The repaint function will force the Java Applet to use the paint method. In the "paint" method, the incremented variables are used as the height and width of an image. When this Java Applet is run, you will see an image grow from nothing to gigantic. The growth of the image will not stop until the Java Applet stops running. You can use the above code example to create a zoom-in effect for pictures. I hope this simple Java thread tutorial proved helpful. Thank you for visiting RoadDust's Java thread tutorial. |
||