DeepSeek Java 多线程打印的12种实现方法

Java 多线程打印的12种实现方法

下面我将为你详细介绍12种不同的Java多线程打印实现方法:

  1. synchronized + wait/notify 方法
java 复制代码
public class Method1_Synchronized {
    private static final Object lock = new Object();
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lock) {
                while (number <= MAX) {
                    if (number % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                lock.notify();
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            synchronized (lock) {
                while (number <= MAX) {
                    if (number % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "Thread-B").start();
    }
}
  1. ReentrantLock + Condition 方法
java 复制代码
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Method2_ReentrantLock {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        new Thread(() -> {
            while (number <= MAX) {
                lock.lock();
                try {
                    if (number % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                        condition.signal();
                    } else {
                        condition.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            while (number <= MAX) {
                lock.lock();
                try {
                    if (number % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                        condition.signal();
                    } else {
                        condition.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "Thread-B").start();
    }
}
  1. Semaphore 信号量方法
java 复制代码
import java.util.concurrent.Semaphore;

public class Method3_Semaphore {
    private static Semaphore semaphoreA = new Semaphore(1);
    private static Semaphore semaphoreB = new Semaphore(0);
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        new Thread(() -> {
            while (number <= MAX) {
                try {
                    semaphoreA.acquire();
                    if (number <= MAX) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    semaphoreB.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            while (number <= MAX) {
                try {
                    semaphoreB.acquire();
                    if (number <= MAX) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    semaphoreA.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-B").start();
    }
}
  1. LockSupport 方法
java 复制代码
import java.util.concurrent.locks.LockSupport;

public class Method4_LockSupport {
    private static int number = 1;
    private static final int MAX = 10;
    private static Thread threadA, threadB;
    
    public static void main(String[] args) {
        threadA = new Thread(() -> {
            while (number <= MAX) {
                if (number % 2 == 1) {
                    System.out.println(Thread.currentThread().getName() + ": " + number++);
                    LockSupport.unpark(threadB);
                } else {
                    LockSupport.park();
                }
            }
        }, "Thread-A");
        
        threadB = new Thread(() -> {
            while (number <= MAX) {
                if (number % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ": " + number++);
                    LockSupport.unpark(threadA);
                } else {
                    LockSupport.park();
                }
            }
        }, "Thread-B");
        
        threadA.start();
        threadB.start();
    }
}
  1. CyclicBarrier 方法
java 复制代码
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Method5_CyclicBarrier {
    private static final int THREAD_COUNT = 2;
    private static CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT);
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        new Thread(() -> {
            while (number <= MAX) {
                try {
                    if (number % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            while (number <= MAX) {
                try {
                    if (number % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-B").start();
    }
}
  1. CountDownLatch 方法
java 复制代码
import java.util.concurrent.CountDownLatch;

public class Method6_CountDownLatch {
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < MAX; i++) {
            CountDownLatch latch = new CountDownLatch(1);
            CountDownLatch nextLatch = new CountDownLatch(1);
            
            new Thread(() -> {
                try {
                    latch.await();
                    if (number <= MAX) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    nextLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "Thread-" + (i + 1)).start();
            
            latch.countDown();
            nextLatch.await();
        }
    }
}
  1. BlockingQueue 方法
java 复制代码
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Method7_BlockingQueue {
    private static BlockingQueue<Integer> queueA = new ArrayBlockingQueue<>(1);
    private static BlockingQueue<Integer> queueB = new ArrayBlockingQueue<>(1);
    private static int number = 1;
    private static final int MAX = 10;
    
    static {
        try {
            queueA.put(0); // 初始化信号
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        new Thread(() -> {
            while (number <= MAX) {
                try {
                    queueA.take();
                    if (number <= MAX) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    queueB.put(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            while (number <= MAX) {
                try {
                    queueB.take();
                    if (number <= MAX) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    queueA.put(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-B").start();
    }
}
  1. Phaser 方法
java 复制代码
import java.util.concurrent.Phaser;

public class Method8_Phaser {
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        Phaser phaser = new Phaser(2);
        
        new Thread(() -> {
            while (number <= MAX) {
                if (number % 2 == 1) {
                    System.out.println(Thread.currentThread().getName() + ": " + number++);
                }
                phaser.arriveAndAwaitAdvance();
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            while (number <= MAX) {
                if (number % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ": " + number++);
                }
                phaser.arriveAndAwaitAdvance();
            }
        }, "Thread-B").start();
    }
}
  1. Exchanger 方法
java 复制代码
import java.util.concurrent.Exchanger;

public class Method9_Exchanger {
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        Exchanger<Boolean> exchanger = new Exchanger<>();
        
        new Thread(() -> {
            boolean flag = true;
            while (number <= MAX) {
                try {
                    if (number % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    flag = exchanger.exchange(flag);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            boolean flag = false;
            while (number <= MAX) {
                try {
                    if (number % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ": " + number++);
                    }
                    flag = exchanger.exchange(flag);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread-B").start();
    }
}
  1. CompletableFuture 方法
java 复制代码
import java.util.concurrent.CompletableFuture;

public class Method10_CompletableFuture {
    private static int number = 1;
    private static final int MAX = 10;
    
    public static void main(String[] args) {
        CompletableFuture<Void> future = CompletableFuture.completedFuture(null);
        
        for (int i = 1; i <= MAX; i++) {
            final int current = i;
            future = future.thenRunAsync(() -> {
                System.out.println(Thread.currentThread().getName() + ": " + current);
            });
        }
        
        future.join();
    }
}
  1. 线程池 + Future 方法
java 复制代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Method11_ThreadPool {
    private static final int MAX = 10;
    
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        
        Future<?> future1 = executor.submit(() -> {
            for (int i = 1; i <= MAX; i += 2) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        });
        
        Future<?> future2 = executor.submit(() -> {
            for (int i = 2; i <= MAX; i += 2) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        });
        
        future1.get();
        future2.get();
        executor.shutdown();
    }
}
  1. AtomicInteger + 自旋锁方法
java 复制代码
import java.util.concurrent.atomic.AtomicInteger;

public class Method12_AtomicInteger {
    private static AtomicInteger number = new AtomicInteger(1);
    private static final int MAX = 10;
    private static volatile int turn = 1; // 1: Thread-A, 2: Thread-B
    
    public static void main(String[] args) {
        new Thread(() -> {
            while (number.get() <= MAX) {
                if (turn == 1 && number.get() <= MAX) {
                    System.out.println(Thread.currentThread().getName() + ": " + number.getAndIncrement());
                    turn = 2;
                }
            }
        }, "Thread-A").start();
        
        new Thread(() -> {
            while (number.get() <= MAX) {
                if (turn == 2 && number.get() <= MAX) {
                    System.out.println(Thread.currentThread().getName() + ": " + number.getAndIncrement());
                    turn = 1;
                }
            }
        }, "Thread-B").start();
    }
}

方法特点对比

方法 优点 缺点 适用场景

synchronized 简单易用,JVM内置 性能相对较低 简单的同步需求

ReentrantLock 功能丰富,性能好 需要手动释放锁 复杂的同步需求

Semaphore 灵活的许可控制 可能产生死锁 资源池、限流

LockSupport 精确控制线程 需要管理park/unpark 需要精细控制线程

CyclicBarrier 可重复使用 需要固定线程数 多阶段任务

CountDownLatch 一次性同步 不可重复使用 主线程等待子线程

BlockingQueue 解耦生产消费 需要管理队列 生产者消费者模式

Phaser 灵活的阶段控制 相对复杂 多阶段复杂任务

Exchanger 线程间数据交换 只能两个线程 配对线程数据交换

CompletableFuture 函数式编程 链式调用复杂 异步编程

线程池 资源管理 需要关闭线程池 任务执行管理

AtomicInteger 无锁操作 自旋消耗CPU 简单的原子操作

这些方法涵盖了Java并发编程的主要工具类,你可以根据具体需求选择合适的方法。

相关推荐
C澒2 分钟前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
铁蛋AI编程实战16 分钟前
通义千问 3.5 Turbo GGUF 量化版本地部署教程:4G 显存即可运行,数据永不泄露
java·人工智能·python
生活很暖很治愈21 分钟前
Linux——孤儿进程&进程调度&大O(1)调度
linux·服务器·ubuntu
晚霞的不甘27 分钟前
CANN 编译器深度解析:UB、L1 与 Global Memory 的协同调度机制
java·后端·spring·架构·音视频
SunnyDays101129 分钟前
使用 Java 冻结 Excel 行和列:完整指南
java·冻结excel行和列
C澒31 分钟前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
HalvmånEver37 分钟前
Linux:线程同步
linux·运维·服务器·线程·同步
喵叔哟38 分钟前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
Zach_yuan39 分钟前
自定义协议:实现网络计算器
linux·服务器·开发语言·网络
摇滚侠40 分钟前
在 SpringBoot 项目中,开发工具使用 IDEA,.idea 目录下的文件需要提交吗
java·spring boot·intellij-idea