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状态,线程终止。

相关推荐
molaifeng4 小时前
Go 语言如何实现高性能网络 I/O:Netpoller 模型揭秘
开发语言·网络·golang
韩师学子--小倪4 小时前
fastjson与gson的toString差异
java·json
Drawing stars4 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
崇山峻岭之间4 小时前
Matlab学习记录33
开发语言·学习·matlab
Evand J4 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
nbsaas-boot4 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
行百里er4 小时前
用 ThreadLocal + Deque 打造一个“线程专属的调用栈” —— Spring Insight 的上下文管理术
java·后端·架构
jllllyuz4 小时前
基于MATLAB的二维波场模拟程序(含PML边界条件)
开发语言·matlab
忆锦紫5 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab
玄〤5 小时前
黑马点评中 VoucherOrderServiceImpl 实现类中的一人一单实现解析(单机部署)
java·数据库·redis·笔记·后端·mybatis·springboot