blog
blog copied to clipboard
线程的创建和状态
trafficstars
线程的创建和状态
线程的创建
线程的创建有两种方式,一种是继承 Thread 类,一种是实现 Runnable 接口
继承 Thread
public class Test {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread run.");
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现 Runnable
public class Test {
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread run.");
}
}
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
上述中我们均调用了 Thread.start() 方法,而不是 Thread.run() 方法。这是因为如果调用 run() 方法,则会在当前线程中串行执行 run() 方法。
如下:
static class MyRunnable implements Runnable {
@Override
public void run() {
try {
// block for some time
Thread.sleep(3000);
System.out.println("Thread run.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
runnable.run();
System.out.println(1);
}
此时,必须等待 runnable.run() 方法串行执行完后,才能输出 1
线程的状态

线程的状态分为如下:
- NEW: 线程被创建,但是尚未执行
- RUNNABLE: 线程进入虚拟机,开始执行并尝试获取 CPUT 资源
- BLOCKED: 线程阻塞,等待获取锁
- WAITING: 线程进入无限期等待。如线程中通过 wait() 方法等待 notify() 方法
- TIMED_WAITING: 进入等待状态(有限期),如 sleep(int t) 使线程休眠
- TERMINATED: 线程结束。
这里要简单说一下线程的中断:
-
当线程处于
WAITING、TIMED_WAITING状态时(如调用了 wait()、join()、sleep() 等方法将会进入此两种状态),调用 Thread.interrupt 方法,则线程的中断状态将被清除,并抛出InterruptedException异常详情见:https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt--
举例:
public class Test { static class MyThread extends Thread { @Override public void run() { try { Thread.sleep(5000); System.out.println("Thread run."); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); thread.interrupt(); } }此段代码将会抛出
InterruptedException异常 -
如果线程处在
RUNNABLE状态时,通常情况该线程的中断状态会被设置,关于这一块会在“线程中断”中说。