寒假打卡01_1月13日
Java 多线程基础
1. 线程介绍
Java 系统中的线程是操作系统为运行时进程分配的最小扩展单元。Java 编程中的线程基于 Thread
类或实现 Runnable
接口来实现多线程。
2. 创建线程的方式
Java 中实现多线程的主要方法有两种:
2.1 继承 Thread
类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中: " + Thread.currentThread().getName());
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2.2 实现 Runnable
接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable 线程运行: " + Thread.currentThread().getName());
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
2.3 使用 Lambda 表达式创建线程
public class LambdaThread {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Lambda 线程运行: " + Thread.currentThread().getName());
});
thread.start();
}
}
3. 线程状态
Java 线程的状态大致分为以下几种:
- NEW (创建): 线程被创建,但尚未启动
- RUNNABLE (可运行): 线程已经启动,正在等待 CPU 资源
- BLOCKED (阻塞): 线程试图获得锁时,被阻塞
- WAITING (等待): 线程进入等待状态,需要其他线程通知
- TIMED_WAITING (定时等待): 线程进入定时等待状态
- TERMINATED (结束): 线程执行完成或被中止
4. 线程的其他操作
4.1 sleep()
方法
Thread.sleep(ms)
会使得当前线程进入睡眠状态持续指定时间,然后自动回到 RUNNABLE 状态。
class SleepExample {
public static void main(String[] args) throws InterruptedException {
System.out.println("Start");
Thread.sleep(2000);
System.out.println("End");
}
}
4.2 join()
方法
join()
用于等待指定线程执行完成。
class JoinExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("Child Thread Finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
thread.join();
System.out.println("Main Thread Finished");
}
}
4.3 interrupt()
中断线程
可以使用 interrupt()
通知线程被中断,线程可以根据 isInterrupted()
进行处理。
class InterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running...");
}
System.out.println("Thread Interrupted");
});
thread.start();
try {
Thread.sleep(1000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
5. 总结
此文简要介绍了 Java 中的线程基础知识,包括创建线程的三种方式,线程的一些基础操作以及线程的状态等。后续将继续深入探讨线程同步、线程池等高级主题。