线程的状态与转换
- 对于 Java 程序,主线程是 main() 方法执行的线索,对于 Applet 程序,主线程是指挥浏览器加载并执行 Java Applet 程序的线索;
1. 线程状态
- 线程的生命周期指线程从创建到执行完成的整个过程,任何一个线程一般都具有5个状态:创建、就绪、运行、阻塞、终止;
- 创建(NEW):new 和 thread 类或其子类创建了一个线程对象后,调用 start() 方法前;
- 就绪(Runnable):start() 方法后,不一定立即运行,它处于就绪队列中,要等待 JVM 里线程调度器的调度;
- 运行:当线程得到系统的资源后进入运行状态;
- 阻塞(Blocked):处于运行状态的线程让出系统资源,调度器立即调度就绪队列中的另一个线程,阻塞事件后,阻塞线程回到就绪状态;
- 无限等待(Waiting):一个线程在等待另一个线程执行一个(唤醒)动作时,该线程进入 Waiting 状态。进入这个状态后是不能自动唤醒的,必须等待另一个线程调用 notify 或者 notifyAll 方法才能够唤醒。
- 计时等待(Timed Waiting):同 waiting 状态,有几个方法有超时参数,调用他们将进入Timed Waiting 状态。这一状态将一直保持到超时期满或者接收到唤醒通知。带有超时参数的常用方法有 Thread.sleep 、Object.wait;
- 终止(Teminated):线程完成或调用 stop() 方法时;
2. 线程状态转换
a. 线程睡眠
- 用 sleep() 方法必须 catch InterruptedException,同理 wait() ;
- wait() 方法和 sleep() 方法不同:调用 wait() 方法,线程释放资源,调用 sleep() 方法,线程不会释放资源;
class MyThread implements Runnable {
@Override
public void run() {
for (; ; ) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("子进程被中断");
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread t = new Thread(mt);
System.out.println("主线程睡眠1s");
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发出t的interrupt()异常");
t.interrupt(); //interrupt()方法发生打断线程的异常
}
}
/*
输出
主线程睡眠1s
发出t的interrupt()异常
子进程被中断
*/
b. 线程合并
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
System.out.println(Thread.currentThread().getName() + "我的子线程");//获取名字
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("子进程被中断");
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.setName("MyThread: ");//命名
t.start();
try {
System.out.println("主线程休息");
Thread.sleep(1000);
System.out.println("合并子线程");
t.join();//调用子线程的join()后,主线程阻塞,子线程执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*
输出
主线程休息
MyThread: 我的子线程
合并子线程
MyThread: 我的子线程
MyThread: 我的子线程
*/
c. 线程让出
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName());
Thread.yield();//让出CPU资源,进入阻塞状态
}
}
}
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
t1.setName("Thread 1");
t2.setName("Thread 2");
t1.start();
t2.start();
}
}
/*
输出
Thread 1
Thread 2
Thread 1
Thread 2
Thread 1
Thread 2
*/