|
Java™ by example!
|
|
|
What is a thread and how do I create and start one?
A thread allows you to do more things at once. It's like a family sitting at the dinner table with in the middle one big pot of spaghetti (CPU). Every member of the family would be a thread and everybody gets its turn to eat some. For Sun's definition, check here: What is a thread? There are several ways to create a thread. The following are a couple of examples that will each perform the same two tasks: 1) ask for first and last name of user with System.in 2) calculate the sum of all numbers from 1 to 123456789. While the program is waiting for input from the user, it is meanwhile performing the calculation. Method 1 Extend from Thread class, define a public void run() method (the starting point of a thread) and call start on an instance of that class: ThreadExample1.java:
Method 2 Mark the class you want as a thread with the interface Runnable, define a public void run() method (the starting point of a thread), pass the Runnable class to a new instance of a Thread and call start on it: ThreadExample2.java:
Method 3 Compact, anonymous instance: ThreadExample3.java:
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|