11.14
线程的状态:
- NEW(新建):线程被创建但尚未启动。
- RUNNABLE(可运行):线程可以在任意时刻运行。处于这个状态的线程可能正在运行,也可能正在等待CPU分配时间片。
- BLOCKED(阻塞):线程被阻止执行,因为它正在等待监视器锁定。其他线程正在占用所需的锁定,因此线程被阻塞。
- WAITING(等待):线程进入等待状态,直到其他线程显式地唤醒它。线程可以调用Object类的wait()方法、join()方法或Lock类的条件等待方法进入此状态。
- TIMED_WAITING(计时等待):线程进入计时等待状态,等待一段指定的时间。线程可以调用Thread.sleep()方法、Object类的wait()方法、join()方法或Lock类的计时等待方法进入此状态。
- TERMINATED(终止):线程完成了其任务,或者因为异常或其他原因而终止运行。
创建线程的方式:
-
继承Thread类:
// 定义一个继承自Thread类的线程类
class MyThread extends Thread {
public void run() {
// 线程执行的代码
System.out.println("Thread running");
}
}
// 创建线程实例,并启动线程
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
} -
实现Runnable接口:
// 定义一个实现Runnable接口的线程类
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
System.out.println("Thread running");
}
}
// 创建线程实例,并启动线程
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
} -
使用匿名内部类:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
// 线程执行的代码
System.out.println("Thread running");
}
});
thread.start();
}
} -
使用Lambda表达式:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> System.out.println("Thread running"));
thread.start();
}
}

浙公网安备 33010602011771号