Java Threads: The Basics
Method 1: Write a class that implements the Runnable interface (i) Put the thread code in the run() method. (ii) Create a thread object by passing a Runnable object as an argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. Like this: (new Thread(new MyThread())).start(); Simple code sample as follows: [code language="java"] package javathread1; class MyThread implements Runnable { public void run() { //Display info about thread System.out.println(Thread.currentThread()); } } public class JavaThread1 { public static void main(String[] args) { // Create the thread Thread thread1 = new Thread(new MyThread(), "thread 1"); // Start the thread thread1.start(); } } [/code] Method 2: Declare the class to be a Subclass of the Thread class (i) Override the run() method from the Thread class to define the ...