thread | for a specific amount of time using the sleep method | when it has finished its job | Threads | - Create 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.
- Write 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
- Create 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.
| if it is waiting for or executing another function or thread that is blocked | Thread class | 1 or more other threads | to perform a job such as waiting for events or performing a time-consuming job that the program doesn't need to complete before going on | lightweight process | many operating systems and programming languages | 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(); } }
| a thread group which places limitations on the thread to protect it from other threads | object | when its run method returns | thread priority | An object used in multithreaded software systems that represents a sequence of program execution |