Multithreaded Programming
Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread. Each thread defines a separate path of execution.
Java's multithreading system is built upon the Thread class and Runnable interface. To create a new thread, your program will either extend Thread or implement the Runnable interface.
The Thread class defines several methods that help manage threads.
Method | Meaning |
---|---|
getName | Obtain a thread's name. |
getPriority | Obtain a thread's priority. |
isAlive | Determine if a thread is still running. |
join | Wait for a thread to terminate. |
run | Entry point for the thread. |
sleep | Suspend a thread for a period of time. |
start | Start a thread by calling its run method. |
Thread declares several deprecated methods, including stop(). These methods have been deprecated because they are unsafe. Do not use these deprecated methods.
The following code shows a pair of counting threads.
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
int count = 0;
while (count< Integer.MAX_VALUE)
System.out.println(name + ": " + count++);
}
};
Thread thdA = new Thread(r);
Thread thdB = new Thread(r);
thdA.start();
thdB.start();
}
}
The following code sets name to threads.
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
int count = 0;
while (count<Integer.MAX_VALUE) {
System.out.println(name + ": " + count++);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
}
}
}
};
Thread thdA = new Thread(r);
thdA.setName("A");
Thread thdB = new Thread(r);
thdB.setName("B");
thdA.start();
thdB.start();
}
}