|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
How to create a thread
Execution in Java always take form of a thread. In simple programs only one thread occurs, often referred to as the 'main thread'. In some programs though concurrent threads is necessary, or if you are building a Swing application with for example a progress bar you don't want the main thread to handle the updates of the UI. Then you create an additional thread to take care of that. There are two main ways of creating a thread. The first is to extend the Thread class and the second is to implement the Runnable interface. Extending Thread: |
public class MyThread extends Thread { /** * This method is executed when the start() method is called on the thread * so here you will put the 'thread code'. */ public void run() { System.out.println("Thread executed!"); } /** * @param args the command line arguments */ public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); } } |
Implementing the Runnable interface: |
public class MyRunnable implements Runnable { /** * As in the previous example this method is executed * when the start() method is called on the thread * so here you will put the 'thread code'. */ public void run() { System.out.println("Thread executed!"); } /** * @param args the command line arguments */ public static void main(String[] args) { //create a Thread object and pass it an object of type Runnable Thread thread = new Thread(new MyRunnable()); thread.start(); } } |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
