Java多线程编程

多线程简介

多线程是Java中实现并发编程的主要方式,它允许程序同时执行多个任务,提高程序的执行效率。

线程的基本概念

// 创建线程的两种方式 // 1. 继承Thread类 public class MyThread extends Thread { @Override public void run() { System.out.println("线程运行中..."); } } // 2. 实现Runnable接口 public class MyRunnable implements Runnable { @Override public void run() { System.out.println("线程运行中..."); } } // 使用线程 Thread thread1 = new MyThread(); thread1.start(); Thread thread2 = new Thread(new MyRunnable()); thread2.start();

线程生命周期

线程在其生命周期中会经历不同的状态:新建、就绪、运行、阻塞和死亡。

public class ThreadLifecycleDemo { public static void main(String[] args) { Thread thread = new Thread(() -> { System.out.println("线程开始运行"); try { Thread.sleep(1000); // 线程进入阻塞状态 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程结束运行"); }); System.out.println("线程状态:" + thread.getState()); // NEW thread.start(); System.out.println("线程状态:" + thread.getState()); // RUNNABLE try { thread.join(); // 等待线程结束 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程状态:" + thread.getState()); // TERMINATED } }

线程同步

线程同步是确保多个线程安全访问共享资源的重要机制。

// 使用synchronized关键字 public class BankAccount { private double balance; public synchronized void deposit(double amount) { balance += amount; System.out.println("存款:" + amount + ",余额:" + balance); } public synchronized void withdraw(double amount) { if (balance >= amount) { balance -= amount; System.out.println("取款:" + amount + ",余额:" + balance); } else { System.out.println("余额不足"); } } } // 使用Lock接口 public class Counter { private int count = 0; private Lock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; System.out.println("计数:" + count); } finally { lock.unlock(); } } }

线程池

线程池是一种线程使用模式,它通过重用线程来减少线程创建和销毁的开销。

// 使用ExecutorService创建线程池 public class ThreadPoolDemo { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); for (int i = 0; i < 5; i++) { final int taskId = i; executor.submit(() -> { System.out.println("任务 " + taskId + " 开始执行"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("任务 " + taskId + " 执行完成"); }); } executor.shutdown(); try { if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); } } }

并发集合

Java提供了线程安全的集合类,用于在多线程环境中安全地操作数据。

// 使用ConcurrentHashMap ConcurrentHashMap map = new ConcurrentHashMap<>(); // 多线程安全地添加元素 map.put("A", 1); map.put("B", 2); map.put("C", 3); // 原子操作 map.computeIfAbsent("D", k -> 4); map.computeIfPresent("A", (k, v) -> v + 1); // 使用ConcurrentLinkedQueue ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); queue.offer("任务1"); queue.offer("任务2"); queue.offer("任务3"); // 多线程安全地处理队列 while (!queue.isEmpty()) { String task = queue.poll(); System.out.println("处理任务:" + task); }

原子变量

原子变量提供了原子操作,确保多线程环境下的数据一致性。

// 使用AtomicInteger public class AtomicCounter { private AtomicInteger count = new AtomicInteger(0); public void increment() { count.incrementAndGet(); } public void decrement() { count.decrementAndGet(); } public int getCount() { return count.get(); } } // 使用AtomicReference public class AtomicReferenceDemo { private AtomicReference message = new AtomicReference<>("初始消息"); public void updateMessage(String newMessage) { message.set(newMessage); } public String getMessage() { return message.get(); } }

实践练习

练习1:生产者-消费者问题

public class ProducerConsumer {
    private BlockingQueue queue;
    
    // 实现生产者-消费者模式
    public void produce() {
        // 实现生产者逻辑
    }
    
    public void consume() {
        // 实现消费者逻辑
    }
}