1. 线程创建 — 继承Thread和实现Runnable接口

继承Thread类

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程执行:" + Thread.currentThread().getName());
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();  // 启动线程,调用run()
    }
}

实现Runnable接口

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程执行:" + Thread.currentThread().getName());
    }
}

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

2. 线程同步 — 使用synchronized保证线程安全

class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

public class SyncDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("最终计数:" + counter.getCount());  // 2000
    }
}

3. 生产者-消费者模式(基于阻塞队列)

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumerDemo {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

        Thread producer = new Thread(() -> {
            try {
                int value = 0;
                while (true) {
                    queue.put(value);
                    System.out.println("生产: " + value);
                    value++;
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    Integer val = queue.take();
                    System.out.println("消费: " + val);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

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

4. 线程池示例 — 使用ExecutorService

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        Runnable task = () -> {
            System.out.println("线程执行:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignored) {}
        };

        for (int i = 0; i < 10; i++) {
            executor.submit(task);
        }

        executor.shutdown();
    }
}

5. 线程间通信 — 使用wait()notify()

class Data {
    private int number;
    private boolean ready = false;

    public synchronized void produce(int n) throws InterruptedException {
        while (ready) {
            wait();
        }
        this.number = n;
        ready = true;
        System.out.println("生产数据: " + n);
        notify();
    }

    public synchronized int consume() throws InterruptedException {
        while (!ready) {
            wait();
        }
        ready = false;
        System.out.println("消费数据: " + number);
        notify();
        return number;
    }
}

public class WaitNotifyDemo {
    public static void main(String[] args) {
        Data data = new Data();

        Thread producer = new Thread(() -> {
            try {
                int i = 0;
                while (true) {
                    data.produce(i++);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    data.consume();
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

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

总结

以上经典案例涵盖了Java多线程的基本技能点:

  • 线程创建方式(继承Thread vs 实现Runnable)
  • 线程同步和互斥(synchronized
  • 生产者-消费者模式(使用BlockingQueue
  • 线程池管理(ExecutorService
  • 线程间通信(wait/notify

熟练掌握这些案例,能帮助你理解Java多线程核心机制,也方便面试时举例说明。

如果你需要,我还能帮你写:

  • 高级并发工具使用示例(如LockSemaphoreCountDownLatch
  • 线程安全集合示例
  • CompletableFuture异步编程示范

随时告诉我!