Java Multitasking  «Prev  Next»

Lesson 5A simple thread example
ObjectiveExplain how to start a thread.

Simple Thread example in Java

In the example below, all this Thread subclass does is override its run() method to show you that it is indeed working.
class MyClass {  
 public static void main(String[] args) {  
  MyThread t = new MyThread();  
  t.start();  
 }  
}
class MyThread extends Thread {  
 public void run() {  
  System.out.println("running...");  
 }  
} 

The output from this program is simply:
running...

Java Thread Theory

Java code is run in threads. When you start a simple application, such as a traditional Hello World application, the code is run in the main thread. As you would expect, an application needs at least one thread to run. It is possible to create your own threads and whenever you create a new thread, the code provided to run in that thread will run immediately. Considering that it is not physically possible to run more than one piece of code on a single CPU core at any one time, it is the job of the JVM to manage these threads and schedule which thread to run and when.

More Complex Example in Java: Running two blocks of code simultaneously

public class Threads {
 public static void main(String[] args) throws InterruptedException {
  final Thread separateThread = new Thread(new ThreadPrinter());
   separateThread.start();
   for (int i = 0; i < 5; i++) {
    System.out.println("From the main thread: i=" + i  + ", " 
		+ Thread.currentThread().getName());
    Thread.sleep(1000);
   }
 }
}

class ThreadPrinter implements Runnable {
 public void run() {		
  for (int j = 0; j < 5; j++) {
   System.out.println("From the new thread:j=" + j  + ", " 
	 + Thread.currentThread().getName() );
   try {
    Thread.sleep(1000);
   }catch (InterruptedException e) {
     e.printStackTrace();
   }
  } // end - for
 }
}

Morse Code - Exercise

You will implement threads in a Morse code program in the next exercise.
Morse Code - Exercise
When you have finished the exercise, see how well you have followed the material by taking a short quiz.
Creating Starting Java Thread - Quiz