You are on page 1of 10

Multithreading

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

The new object is referred to as a runnable object


4

Inheriting from Thread


The simplest way to create a thread is to inherit from class Thread, which has all the wiring necessary to create and run threads. The most important method for Thread is run( ), which you must override to make the thread do your bidding. Thus, run( ) is the code that will be executed simultaneously with the other threads in a program.

//: 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

Using Runnable Interface


In Java, it is also possible to start a thread on any object that implements the Runnable interface. To implement Runnable, a class is only required to implement a method called run().

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.

Overview of JDBC, Servlets, JSP, JavaBeans, Enterprise JavaBeans Technologies

You might also like