您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Java多线程基础知识点有哪些
## 目录
1. [多线程概述](#一多线程概述)
2. [线程创建方式](#二线程创建方式)
3. [线程生命周期](#三线程生命周期)
4. [线程同步机制](#四线程同步机制)
5. [线程通信](#五线程通信)
6. [线程池技术](#六线程池技术)
7. [并发工具类](#七并发工具类)
8. [线程安全集合](#八线程安全集合)
9. [原子操作类](#九原子操作类)
10. [Java内存模型](#十java内存模型)
11. [常见面试题](#十一常见面试题)
## 一、多线程概述
### 1.1 什么是线程
线程(Thread)是操作系统能够进行运算调度的最小单位,被包含在进程之中,是进程中的实际运作单位。一个进程中可以包含多个线程,所有线程共享进程的资源。
### 1.2 为什么需要多线程
- **提高CPU利用率**:当某个线程等待I/O时,CPU可以执行其他线程
- **改善响应时间**:GUI程序使用多线程保持界面响应
- **简化建模**:每个线程处理独立任务,模型更清晰
### 1.3 Java线程实现原理
Java线程通过java.lang.Thread类实现,底层依赖操作系统原生线程实现:
- Windows系统使用Win32 API
- Linux系统使用pthread库
- macOS系统通过POSIX线程实现
```java
// 获取当前线程信息示例
public class ThreadInfo {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println("线程ID: " + thread.getId());
System.out.println("线程名称: " + thread.getName());
System.out.println("线程优先级: " + thread.getPriority());
System.out.println("线程状态: " + thread.getState());
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("继承Thread类创建的线程");
}
}
// 使用方式
new MyThread().start();
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口创建的线程");
}
}
// 使用方式
new Thread(new MyRunnable()).start();
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "实现Callable接口创建的线程";
}
}
// 使用方式
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
new Thread(futureTask).start();
System.out.println(futureTask.get());
方式 | 优点 | 缺点 |
---|---|---|
继承Thread类 | 编码简单 | 无法继承其他类 |
实现Runnable接口 | 可继承其他类,适合资源共享 | 无返回值 |
实现Callable接口 | 可获取返回值,可抛出异常 | 编码较复杂 |
stateDiagram
[*] --> NEW
NEW --> RUNNABLE: start()
RUNNABLE --> BLOCKED: 等待同步锁
BLOCKED --> RUNNABLE: 获取到锁
RUNNABLE --> WTING: wait()/join()
WTING --> RUNNABLE: notify()/notifyAll()
RUNNABLE --> TIMED_WTING: sleep(n)/wait(n)
TIMED_WTING --> RUNNABLE: 超时结束
RUNNABLE --> TERMINATED: run()结束
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
synchronized (ThreadStateDemo.class) {
ThreadStateDemo.class.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("创建后状态: " + thread.getState()); // NEW
thread.start();
System.out.println("启动后状态: " + thread.getState()); // RUNNABLE
Thread.sleep(100);
System.out.println("sleep时状态: " + thread.getState()); // TIMED_WTING
Thread.sleep(1000);
System.out.println("wait时状态: " + thread.getState()); // WTING
thread.interrupt();
thread.join();
System.out.println("结束后状态: " + thread.getState()); // TERMINATED
}
}
public synchronized void method() {
// 同步代码
}
public void method() {
synchronized(this) {
// 同步代码
}
}
public static synchronized void staticMethod() {
// 同步代码
}
// 或
synchronized(MyClass.class) {
// 同步代码
}
Lock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
// 同步代码
} finally {
lock.unlock();
}
}
ReadWriteLock rwLock = new ReentrantReadWriteLock();
public void read() {
rwLock.readLock().lock();
try {
// 读操作
} finally {
rwLock.readLock().unlock();
}
}
public void write() {
rwLock.writeLock().lock();
try {
// 写操作
} finally {
rwLock.writeLock().unlock();
}
}
private volatile boolean flag = false;
public void setFlag() {
flag = true; // 保证对其他线程立即可见
}
class Message {
private String content;
private boolean empty = true;
public synchronized String read() {
while(empty) {
try {
wait();
} catch (InterruptedException e) {}
}
empty = true;
notifyAll();
return content;
}
public synchronized void write(String content) {
while(!empty) {
try {
wait();
} catch (InterruptedException e) {}
}
empty = false;
this.content = content;
notifyAll();
}
}
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println(Thread.currentThread().getName());
});
}
executor.shutdown();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // 核心线程数
5, // 最大线程数
60, // 空闲线程存活时间
TimeUnit.SECONDS, // 时间单位
new ArrayBlockingQueue<>(10), // 工作队列
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println("子线程执行");
latch.countDown();
}).start();
}
latch.await();
System.out.println("主线程继续执行");
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("所有线程到达屏障");
});
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
System.out.println("线程准备就绪");
barrier.await();
System.out.println("线程继续执行");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println("线程获取许可");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}).start();
}
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.putIfAbsent("key1", 2);
System.out.println(map.get("key1")); // 输出1
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item1");
list.addIfAbsent("item1");
System.out.println(list.size()); // 输出1
BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
queue.put("item1");
String item = queue.take();
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
counter.compareAndSet(1, 2);
LongAdder adder = new LongAdder();
adder.increment();
adder.add(10);
System.out.println(adder.sum());
AtomicReference<String> ref = new AtomicReference<>("old");
ref.compareAndSet("old", "new");
特性 | synchronized | Lock |
---|---|---|
实现方式 | JVM层面实现 | Java API实现 |
锁释放 | 自动释放 | 必须手动释放 |
中断响应 | 不支持 | 支持 |
公平锁 | 非公平 | 可配置 |
条件变量 | 单一 | 多个 |
(因篇幅限制,此处展示核心内容框架,完整文章需补充更多示例、原理分析和实践建议以达到约8850字要求) “`
注:完整文章需要: 1. 扩展每个知识点的详细说明 2. 增加更多代码示例 3. 添加性能对比数据 4. 补充实际应用场景 5. 加入调试和问题排查技巧 6. 增加与最新Java版本的特性对比 7. 补充更多图表和示意图 8. 添加参考资料和延伸阅读建议
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。