多线程知识点

一、基础概念

1. 线程的定义

线程是程序执行的最小单元,一个进程可以包含多个线程,这些线程共享进程的内存空间和资源。在Java应用中,线程可以并发执行任务,提高程序的运行效率。

2. 进程 vs 线程
特性进程线程
定义独立运行的程序,具有独立地址空间进程内的执行单元,共享地址空间
资源占用较高(独立内存、文件句柄等)较低(共享进程资源)
创建/销毁开销
通信方式进程间通信(IPC,如管道、消息队列)共享内存、同步机制
典型场景多应用运行(如浏览器、编辑器)Web服务器、并发任务处理
3. 并发 vs 并行
  • 并发:多个任务在同一个CPU上切换执行(宏观同时)。
  • 并行:多个任务真正同时运行(多核CPU)。

二、线程的创建

1. 继承Thread类
class MyThread extends Thread {
    public void run() {
        System.out.println("Hello from thread: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

优缺点

  • 优点:简单直接。
  • 缺点:无法继承其他类,扩展性差。
2. 实现Runnable接口
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable is running: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}

优缺点

  • 优点:可以通过实现接口实现多线程,不受Java单继承机制的限制;代码更具可重用性,业务逻辑和线程控制分离。
  • 缺点:与继承Thread类相比,启动线程需要额外创建Thread对象。
3. 实现Callable接口(带返回值)
import java.util.concurrent.*;

class MyCallable implements Callable<Integer> {
    public Integer call() throws Exception {
        return 123;
    }
}

public class Main {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<Integer> future = pool.submit(new MyCallable());
        try {
            System.out.println("Result: " + future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        pool.shutdown();
    }
}
4. 使用Lambda表达式
public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("Lambda thread: " + Thread.currentThread().getName());
        });
        t.start();
    }
}

三、线程的生命周期

1. 生命周期状态
  • 新建(New):线程被创建,但尚未启动。这时它还没有分配CPU时间。
  • 就绪(Runnable):线程已经准备好等待CPU的分配,此时线程可以执行,但具体何时执行取决于线程调度器。
  • 运行(Running):线程已经获得了CPU时间片,正在执行任务。
  • 阻塞(Blocked):线程由于等待某些资源(如I/O操作、锁等)而暂时停止运行。当资源变得可用时,线程重新进入就绪状态。
  • 终止(Terminated):线程已完成任务或因异常终止,生命周期结束。
2. 常用方法对生命周期的影响
  • start():使线程进入就绪状态。
  • join():让一个线程等待另一个线程执行完毕。
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("线程执行: " + Thread.currentThread().getName());
            }
        });
        thread.start();
        thread.join();
        System.out.println("主线程继续执行");
    }
}

四、线程同步

1. 线程安全问题

当多个线程同时访问共享资源时,可能会导致数据不一致的问题,如竞态条件、死锁等。

2. 同步机制
(1)synchronized关键字
class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}
(2)ReentrantLock
import java.util.concurrent.locks.ReentrantLock;

class Counter {
    private int count = 0;
    private ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}
(3)volatile关键字
class VolatileExample {
    private volatile boolean flag = false;

    public void toggleFlag() {
        flag = !flag;
    }
}

五、线程间通信

1. wait() 和 notify() 方法
class MessageBox {
    private String message;
    private boolean hasMessage = false;

    public synchronized void put(String msg) throws InterruptedException {
        while (hasMessage) wait();
        message = msg;
        hasMessage = true;
        notifyAll();
    }

    public synchronized String take() throws InterruptedException {
        while (!hasMessage) wait();
        hasMessage = false;
        notifyAll();
        return message;
    }
}
2. BlockingQueue
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;

class ProducerConsumer {
    private final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

    public void produce() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            queue.put(i);
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            int value = queue.take();
            // 处理value
        }
    }
}

六、线程池

1. 线程池的优势
  • 减少线程创建和销毁的开销。
  • 提高程序性能。
  • 简化线程管理。
2. 创建线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        pool.submit(() -> {
            System.out.println("任务由线程池处理");
        });
        pool.shutdown();
    }
}
3. 线程池核心参数
  • corePoolSize:核心线程数。
  • maximumPoolSize:最大线程数。
  • keepAliveTime:空闲线程存活时间。
  • workQueue:任务队列。

七、并发工具类

1. CountDownLatch
import java.util.concurrent.CountDownLatch;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        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("所有任务完成");
    }
}
2. CyclicBarrier
import java.util.concurrent.CyclicBarrier;

public class Main {
    public static void main(String[] args) {
        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();
        }
    }
}
3. Semaphore
import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("线程获得许可");
                    Thread.sleep(1000);
                    System.out.println("线程释放许可");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

八、常见问题与解决方案

1. 线程安全问题
  • 问题:多个线程同时访问共享资源时,可能导致数据不一致。
  • 解决方案:使用同步机制(synchronized、ReentrantLock)、原子类(AtomicInteger等)、并发集合(ConcurrentHashMap等)。
2. 死锁
  • 问题:多个线程相互等待对方释放资源,导致程序无法继续执行。
  • 解决方案:避免锁嵌套、使用定时锁(tryLock())、按顺序获取锁。
3. 线程饥饿
  • 问题:某些线程因为优先级低或资源竞争激烈而长时间得不到执行机会。
  • 解决方案:合理设置线程优先级、使用公平锁。
4. 上下文切换开销
  • 问题:频繁的上下文切换会降低程序的性能。
  • 解决方案:减少线程数量、使用线程池、优化任务分配。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值