2016 - 2024

感恩一路有你

java各个线程的生命周期

浏览量:3313 时间:2023-12-19 16:39:45 作者:采采

一、线程的创建:

在Java中,创建线程的方式主要有两种:继承Thread类和实现Runnable接口。当创建了一个线程对象后,线程并没有立即执行,而是处于新建状态。

示例代码:

```java

public class MyThread extends Thread {

public void run() {

("MyThread is running");

}

}

public class MyRunnable implements Runnable {

public void run() {

("MyRunnable is running");

}

}

public class Main {

public static void main(String[] args) {

Thread thread1 new MyThread();

Thread thread2 new Thread(new MyRunnable());

();

();

}

}

```

二、线程的运行:

当调用线程对象的start()方法后,线程进入到可运行状态。在可运行状态下,线程可以被调度并执行run()方法中的代码。

示例代码:

```java

public class MyThread extends Thread {

public void run() {

for (int i 0; i < 5; i ) {

("MyThread is running");

}

}

}

public class Main {

public static void main(String[] args) {

Thread thread new MyThread();

();

}

}

```

三、线程的阻塞:

线程可能会由于某些原因进入阻塞状态,阻塞状态下的线程暂时停止执行,并且不会占用CPU资源。常见的阻塞情况包括等待IO操作、等待锁、等待其他线程唤醒等。

示例代码:

```java

public class MyThread extends Thread {

public void run() {

synchronized (this) {

try {

wait(); //线程进入阻塞状态,等待被唤醒

} catch (InterruptedException e) {

();

}

}

("MyThread is running after being unblocked");

}

}

public class Main {

public static void main(String[] args) {

Thread thread new MyThread();

();

synchronized (thread) {

(); //唤醒线程

}

}

}

```

四、线程的等待:

线程可以通过调用wait()方法进入等待状态,等待其他线程发出notify或notifyAll信号来唤醒。

示例代码:

```java

public class MyThread extends Thread {

public void run() {

synchronized (this) {

try {

wait(); //线程进入等待状态,直到被其他线程唤醒

} catch (InterruptedException e) {

();

}

}

("MyThread is running after being woken up");

}

}

public class Main {

public static void main(String[] args) {

Thread thread new MyThread();

();

synchronized (thread) {

(); //唤醒线程

}

}

}

```

五、线程的销毁:

线程执行完run()方法中的代码后,线程进入终止状态,销毁并释放资源。

示例代码:

```java

public class MyThread extends Thread {

public void run() {

for (int i 0; i < 5; i ) {

("MyThread is running");

}

}

}

public class Main {

public static void main(String[] args) {

Thread thread new MyThread();

();

try {

(); //等待线程执行完毕

} catch (InterruptedException e) {

();

}

("Main thread is exiting");

}

}

```

总结:

本文详细介绍了Java线程的生命周期,包括线程的创建、运行、阻塞、等待和销毁等不同状态。通过示例代码和详细说明,帮助读者深入理解和掌握多线程编程。希望本文能够对读者在使用Java进行多线程开发时有所帮助。

Java线程 生命周期 线程状态 创建 运行 阻塞 等待 销毁

版权声明:本文内容由互联网用户自发贡献,本站不承担相关法律责任.如有侵权/违法内容,本站将立刻删除。