Professional Documents
Culture Documents
Lecture 12
Multiple Threads
Often, you need to turn a program into separate, independently-running subtasks. Each of these independent subtasks is called a thread, and you program as if each thread runs by itself and has the CPU to itself. Some underlying mechanism is actually dividing up the CPU time for you, but in general, you dont have to think about it, which makes programming with multiple threads a much easier task.
2
Multithreading
When your program executes as an application, the JVM starts a thread for the main() method When your program runs as an applet, the web browser starts a thread to run the applet Each new thread is an object of a class that:
1. Extends the Thread class OR2. Implements the Runnable interface
//: c14:SimpleThread.java // Very simple Threading example. public class SimpleThread extends Thread { private int countDown = 5; private static int threadCount = 0; private int threadNumber = ++threadCount; public SimpleThread() { System.out.println("Making " + threadNumber); } public void run() { while(true) { System.out.println("Thread " + threadNumber + "(" + countDown + ")"); if(--countDown == 0) return; } } public static void main(String[] args) { for(int i = 0; i < 5; i++) new SimpleThread().start(); System.out.println("All Threads Started"); } } // end of class
Multithreading
Some other Useful Methods :
setPriority() : To set the priority of any thread getPriority() : To get the priority of any thread
Whenever the thread scheduler tries to select a new thread for execution, it picks the highest priority that can be run.
Multithreading
The thread keeps running until one of the following things takes place :
It yields by invoking the yield method. It is no longer runnable(terminates or enters the blocked state). A higher-priority thread has become runnable.