Java基础 - 多线程

多线程

创建新线程

实例化一个Thread实例,然后调用它的start()方法

java 复制代码
Thread t = new Thread();
t.start(); // 启动新线程

从Thread派生一个自定义类,然后覆写run()方法:

java 复制代码
public class Main {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start(); // 启动新线程
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}

创建Thread实例时,传入一个Runnable实例:

java 复制代码
public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start(); // 启动新线程
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}

用Java8引入的lambda语法进一步简写为:

java 复制代码
public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("start new thread!");
        });
        t.start(); // 启动新线程
    }
}

sleep()传入的参数是毫秒。

调整暂停时间的大小,我们可以看到main线程和t线程执行的先后顺序。

线程的优先级

可以对线程设定优先级,设定优先级的方法是:

java 复制代码
Thread.setPriority(int n) // 1~10, 默认值5

线程的状态

New:新创建的线程,尚未执行;

Runnable:运行中的线程,正在执行run()方法的Java代码;

Blocked:运行中的线程,因为某些操作被阻塞而挂起;

Waiting:运行中的线程,因为某些操作在等待中;

Timed Waiting:运行中的线程,因为执行sleep()方法正在计时等待;

Terminated:线程已终止,因为run()方法执行完毕。

当线程启动后,它可以在Runnable、Blocked、Waiting和Timed Waiting这几个状态之间切换,直到最后变成Terminated状态,线程终止。

相关推荐
骑着蜗牛撵大象3277 分钟前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕10 分钟前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
Dxy12393102161 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷1 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang1 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
三无少女指南2 小时前
从这里开始:Java 后端与 AI 工程的三条阅读路线
java·学习路线·ai工程
香蕉大香蕉(06敬畏市场)2 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股
nice_lcj5202 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
骑着蜗牛撵大象3273 小时前
2026 后端 AI 工程化:Spring AI 管调用、MCP 管工具、Agent 内嵌管自治
java·人工智能·后端·spring·ai·可观测性·mcp
tryxr3 小时前
JVM 垃圾回收机制
java·jvm·gc·垃圾回收