《Java开发十日速成:零基础保姆级教程(附20000字实战+流程图)》
副标题:挑战高薪!十天掌握Java核心技能,小白也能写出企业级代码
Day7:多线程与并发编程
学习目标:
- 掌握线程的创建与生命周期管理
- 理解线程同步与锁优化技术
- 学习线程池的使用及参数调优
- 完成实战项目:银行转账模拟(死锁预防与并发控制)
7.1 线程基础
线程的创建方式
Java中创建线程的两种核心方式:
- 继承
Thread
类 - 实现
Runnable
接口
代码示例:
// 方式1:继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
// 方式2:实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("任务执行中:" + Thread.currentThread().getName());
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.start();
MyRunnable task = new MyRunnable();
Thread thread2 = new Thread(task);
thread2.start();
}
}
线程生命周期
线程状态转换流程图: