esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

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:

This code sample is only viewable to esus.com members
Login or become a member!



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:

This code sample is only viewable to esus.com members
Login or become a member!



Method 3

Compact, anonymous instance:

ThreadExample3.java:

This code sample is only viewable to esus.com members
Login or become a member!






Further Information
Author of answer: Joris Van den Bogaert

Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.