Thread introduction
In this chapter you will learn:
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.
Thread in action
The following code shows a pair of counting threads.
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override/*ja v a2 s .c o m*/
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();
}
}
Next chapter...
What you will learn in the next chapter: