thread in Java | the same time as another thread | - Creating a class to contain the code that will control the thread. This can be made a subclass of Thread class, or else it can implement the interface Runnable.
- Writing a method called run in your class. The run method will normally take a reasonably long time to execute - perhaps it waits for input in a loop. When the thread is started, this run method executes, concurrently with any other thread in the system. When the run method ends, the thread terminates
- Creating an instance of Thread class, or your subclass of Thread class, and invoking the start operation on this instance. If you implemented the interface Runnable, you have to pass an instance of your class to the constructor of Thread class.
| thread in Java | thread | The Basics of Java | public class ThreadExample implements Runnable { private int counterNumber; // Identifies the thread private int counter; // How far the thread has executed private int limit; // Where counter will stop private long delay; // Pause in execution of thread in milisecs // Constructor private ThreadExample(int countTo, int number, long delay) { counter = 0; limit = countTo; counterNumber = number; this.delay = delay; } //The run method; when this finishes, the thread terminates public void run() { try { while (counter <= limit) { System.out.println("Counter " + counterNumber + " is now at " + counter++); Thread.sleep(delay); } } catch(InterruptedException e) {} } // The main method: Executed when the program is started public static void main(String[] args) //Create 3 threads and run them Thread firstThread = new Thread(new ThreadExample(5, 1, 66)); Thread secondThread = new Thread(new ThreadExample(5, 2, 45)); Thread thirdThread = new Thread(new ThreadExample(5, 3, 80)); firstThread.start(); secondThread.start(); thirdThread.start(); } }
| many operating systems and programming languages |