11.14

线程的状态:

  1. NEW(新建):线程被创建但尚未启动。
  2. RUNNABLE(可运行):线程可以在任意时刻运行。处于这个状态的线程可能正在运行,也可能正在等待CPU分配时间片。
  3. BLOCKED(阻塞):线程被阻止执行,因为它正在等待监视器锁定。其他线程正在占用所需的锁定,因此线程被阻塞。
  4. WAITING(等待):线程进入等待状态,直到其他线程显式地唤醒它。线程可以调用Object类的wait()方法、join()方法或Lock类的条件等待方法进入此状态。
  5. TIMED_WAITING(计时等待):线程进入计时等待状态,等待一段指定的时间。线程可以调用Thread.sleep()方法、Object类的wait()方法、join()方法或Lock类的计时等待方法进入此状态。
  6. TERMINATED(终止):线程完成了其任务,或者因为异常或其他原因而终止运行。

创建线程的方式:

  1. 继承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();
    }
    }

  2. 实现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();
    }
    }

  3. 使用匿名内部类:
    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();
    }
    }

  4. 使用Lambda表达式:
    public class Main {
    public static void main(String[] args) {
    Thread thread = new Thread(() -> System.out.println("Thread running"));
    thread.start();
    }
    }

posted @ 2025-11-14 19:10  萌新求职记录  阅读(8)  评论(0)    收藏  举报