← 返回首页

Java多线程基础:并发编程入门

📂 java ⏱ 3 min 508 words

Java多线程基础:并发编程入门

概述

多线程编程是Java的重要特性,它允许程序同时执行多个任务。理解线程的概念和使用,是编写高效Java程序的基础。

1. 线程创建方式

// 方式1:继承Thread类
public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(getName() + ": " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}
// 方式2:实现Runnable接口
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "Thread-1");
        Thread t2 = new Thread(new MyRunnable(), "Thread-2");
        t1.start();
        t2.start();
    }
}

2. 线程生命周期

public class ThreadStateDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } 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("等待: " + thread.getState());  // TIMED_WAITING
        thread.join();
        System.out.println("终止: " + thread.getState());  // TERMINATED
    }
}

3. 线程同步

public class SynchronizedDemo {
    private int count = 0;
    private final Object lock = new Object();

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

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedDemo demo = new SynchronizedDemo();
        Thread[] threads = new Thread[10];

        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    demo.increment();
                }
            });
            threads[i].start();
        }

        for (Thread t : threads) {
            t.join();
        }

        System.out.println("Count: " + demo.getCount());  // 10000
    }
}

4. 线程通信

// wait/notify实现生产者-消费者
public class ProducerConsumer {
    private final Queue<Integer> queue = new LinkedList<>();
    private final int capacity = 10;

    public synchronized void produce(int item) throws InterruptedException {
        while (queue.size() == capacity) {
            wait();
        }
        queue.offer(item);
        System.out.println("生产: " + item + ", 队列大小: " + queue.size());
        notifyAll();
    }

    public synchronized int consume() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();
        }
        int item = queue.poll();
        System.out.println("消费: " + item + ", 队列大小: " + queue.size());
        notifyAll();
        return item;
    }

    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread producer = new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    pc.produce(i);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    pc.consume();
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}

5. 线程安全问题

// 非线程安全示例
public class UnsafeCounter {
    private int count = 0;

    public void increment() {
        count++;  // 复合操作:读-改-写
    }

    public int getCount() {
        return count;
    }
}

// 线程安全示例
import java.util.concurrent.atomic.AtomicInteger;

public class SafeCounter {
    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        count.incrementAndGet();
    }

    public int getCount() {
        return count.get();
    }
}

最佳实践

  1. 优先使用Runnable:避免单继承限制
  2. 合理使用同步:避免过度同步影响性能
  3. 使用线程池:避免频繁创建销毁线程
  4. 避免死锁:注意锁的获取顺序
  5. 使用原子类:简单操作优先使用Atomic*

总结

多线程编程是Java的核心特性之一,掌握线程的创建、同步和通信机制,是编写高效并发程序的基础。合理使用多线程可以提高程序的性能和响应速度。