java多线程知识点详解
时间: 2025-07-28 22:20:53 浏览: 9
<think>我们首先讲解Java多线程的核心知识点,然后给出相关代码示例和解释,最后提出相关问题。Java多线程知识点详解:1.**线程的创建**:-继承Thread类,重写run方法。-实现Runnable接口,实现run方法,然后将Runnable实例作为参数传递给Thread对象。-实现Callable接口(可以返回结果或抛出异常),需要结合FutureTask使用。2.**线程的生命周期**:-新建(New)-就绪(Runnable)-运行(Running)-阻塞(Blocked)-死亡(Dead)3.**线程同步与锁**:-synchronized关键字:可以同步方法或代码块。-Lock接口及其实现类(如ReentrantLock):提供了更灵活的锁操作。4.**线程间通信**:-wait(),notify(),notifyAll()(必须在同步块或同步方法中使用,且由同步锁对象调用)-使用Condition(与Lock配合使用)的await(),signal(),signalAll()5.**线程池**:-使用Executors工厂类创建线程池(如newFixedThreadPool,newCachedThreadPool等)-使用ThreadPoolExecutor自定义线程池。6.**并发工具类**:-CountDownLatch:允许一个或多个线程等待其他线程完成操作。-CyclicBarrier:让一组线程到达一个屏障时被阻塞,直到最后一个线程到达屏障时,屏障才会开门。-Semaphore:控制同时访问特定资源的线程数量。-Exchanger:用于两个线程交换数据。7.**原子类**:-如AtomicInteger,AtomicLong等,用于实现原子操作。8.**并发集合**:-ConcurrentHashMap,CopyOnWriteArrayList,BlockingQueue等。下面我们通过代码示例来展示部分知识点。###示例1:创建线程的两种方式####方式1:继承Thread类```javapublicclassMyThreadextendsThread{@Overridepublicvoidrun(){System.out.println("线程运行中,继承Thread类");}publicstaticvoidmain(String[]args){MyThreadthread=newMyThread();thread.start();//启动线程}}```####方式2:实现Runnable接口```javapublicclassMyRunnableimplementsRunnable{@Overridepublicvoidrun(){System.out.println("线程运行中,实现Runnable接口");}publicstaticvoidmain(String[]args){Threadthread=newThread(newMyRunnable());thread.start();}}```###示例2:使用Callable和FutureTask```javaimportjava.util.concurrent.Callable;importjava.util.concurrent.FutureTask;publicclassMyCallableimplementsCallable<String>{@OverridepublicStringcall()throwsException{return"Callable返回结果";}publicstaticvoidmain(String[]args)throwsException{FutureTask<String>futureTask=newFutureTask<>(newMyCallable());Threadthread=newThread(futureTask);thread.start();System.out.println(futureTask.get());//获取返回结果}}```###示例3:使用synchronized实现同步```javapublicclassSynchronizedExample{privateintcount=0;publicsynchronizedvoidincrement(){//同步方法count++;}publicvoidincrementBlock(){synchronized(this){//同步代码块count++;}}publicstaticvoidmain(String[]args)throwsInterruptedException{SynchronizedExampleexample=newSynchronizedExample();Threadt1=newThread(()->{for(inti=0;i<1000;i++){example.increment();}});Threadt2=newThread(()->{for(inti=0;i<1000;i++){example.incrementBlock();}});t1.start();t2.start();t1.join();t2.join();System.out.println(example.count);//输出2000}}```###示例4:使用ReentrantLock```javaimportjava.util.concurrent.locks.ReentrantLock;publicclassLockExample{privateintcount=0;privateReentrantLocklock=newReentrantLock();publicvoidincrement(){lock.lock();try{count++;}finally{lock.unlock();}}publicstaticvoidmain(String[]args)throwsInterruptedException{LockExampleexample=newLockExample();Threadt1=newThread(()->{for(inti=0;i<1000;i++){example.increment();}});Threadt2=newThread(()->{for(inti=0;i<1000;i++){example.increment();}});t1.start();t2.start();t1.join();t2.join();System.out.println(example.count);//输出2000}}```###示例5:线程池的使用```javaimportjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoolExample{publicstaticvoidmain(String[]args){ExecutorServiceexecutor=Executors.newFixedThreadPool(2);for(inti=0;i<5;i++){executor.execute(()->{System.out.println("线程"+Thread.currentThread().getName()+"执行任务");});}executor.shutdown();}}```###示例6:CountDownLatch使用```javaimportjava.util.concurrent.CountDownLatch;publicclassCountDownLatchExample{publicstaticvoidmain(String[]args)throwsInterruptedException{intworkerCount=3;CountDownLatchlatch=newCountDownLatch(workerCount);for(inti=0;i<workerCount;i++){newThread(()->{System.out.println(Thread.currentThread().getName()+"完成任务");latch.countDown();}).start();}latch.await();System.out.println("所有任务完成");}}```以上代码示例涵盖了多线程的基础和部分高级用法。接下来,我们提出一些相关问题。§§相关问题§§:1.请详细解释Java中的线程状态以及状态之间的转换。2.什么是死锁?如何避免死锁?请给出一个死锁的代码示例。3.请比较synchronized和ReentrantLock的异同点。4.线程池的参数有哪些?如何合理配置线程池参数?</think>### Java多线程知识点详解
Java多线程是并发编程的核心,主要涉及线程创建、同步机制、线程通信和线程池等。以下是关键知识点及代码示例:
#### 1. **线程创建**
- **继承Thread类**:重写`run()`方法
- **实现Runnable接口**:更灵活(推荐)
- **实现Callable接口**:可返回结果和抛异常
```java
// 方式1:继承Thread
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
// 方式2:实现Runnable
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running: " + Thread.currentThread().getName());
}
}
// 方式3:实现Callable(带返回值)
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Result from " + Thread.currentThread().getName();
}
}
public class Main {
public static void main(String[] args) throws Exception {
// 启动Thread
new MyThread().start();
// 启动Runnable
new Thread(new MyRunnable()).start();
// 启动Callable
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get()); // 获取返回值
executor.shutdown();
}
}
```
#### 2. **线程同步**
使用`synchronized`或`Lock`解决竞态条件:
```java
// 同步方法
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
// 同步代码块
public void add() {
synchronized(this) {
count++;
}
}
// 使用ReentrantLock
import java.util.concurrent.locks.*;
class SafeCounter {
private final Lock lock = new ReentrantLock();
private int value = 0;
public void increment() {
lock.lock();
try {
value++;
} finally {
lock.unlock();
}
}
}
```
#### 3. **线程通信**
使用`wait()`/`notify()`实现生产者-消费者模型:
```java
class Buffer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity = 2;
public synchronized void produce(int item) throws InterruptedException {
while (queue.size() == capacity) {
wait(); // 缓冲区满时等待
}
queue.add(item);
notifyAll(); // 唤醒消费者
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
wait(); // 缓冲区空时等待
}
int item = queue.poll();
notifyAll(); // 唤醒生产者
return item;
}
}
```
#### 4. **线程池**
使用`ExecutorService`管理线程:
```java
import java.util.concurrent.*;
public class ThreadPoolDemo {
public static void main(String[] args) {
// 创建固定大小线程池
ExecutorService pool = Executors.newFixedThreadPool(3);
// 提交任务
for (int i = 0; i < 5; i++) {
pool.execute(() -> {
System.out.println("Task executed by " + Thread.currentThread().getName());
});
}
// 关闭线程池
pool.shutdown();
}
}
```
#### 5. **并发工具类**
- **CountDownLatch**:等待多个任务完成
```java
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
// 执行任务
latch.countDown();
}).start();
}
latch.await(); // 阻塞直到计数器归零
```
- **CyclicBarrier**:线程到达屏障时等待
```java
CyclicBarrier barrier = new CyclicBarrier(3, () ->
System.out.println("All threads reached barrier"));
for (int i = 0; i < 3; i++) {
new Thread(() -> {
barrier.await(); // 等待其他线程
}).start();
}
```
#### 6. **原子操作**
使用`AtomicInteger`等原子类:
```java
import java.util.concurrent.atomic.*;
AtomicInteger atomicInt = new AtomicInteger(0);
atomicInt.incrementAndGet(); // 原子自增
```
#### 7. **线程状态**
Java线程的6种状态:
1. **NEW**:新建未启动
2. **RUNNABLE**:可运行(包括就绪和运行中)
3. **BLOCKED**:等待监视器锁
4. **WAITING**:无限期等待(`wait()`/`join()`)
5. **TIMED_WAITING**:限期等待(`sleep()`/`wait(timeout)`)
6. **TERMINATED**:终止
---
阅读全文
相关推荐














