精通 Java 多线程:线程控制、同步与并发工具

发布: (2025年12月2日 GMT+8 17:00)
2 min read
原文: Dev.to

Source: Dev.to

线程控制

Java 提供了内置的方法来控制线程的执行。

关键方法

  • sleep() – 暂停当前线程指定的时间。
  • join() – 等待另一个线程结束。
  • yield() – 建议当前线程让出执行权,以便其他线程运行。

示例

package ayshriv;

public class MasteringBackend {
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            for (int i = 1; i  {
            for (int i = 0; i  {
            for (int i = 0; i  {
            for (int i = 0; i  {
            for (int i = 0; i  {
            try {
                for (int i = 1; i  {
            try {
                for (int i = 1; i  {
    while (true) {
        try {
            System.out.println("Daemon thread working...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            break;
        }
    }
});
daemon.setDaemon(true);
daemon.start();

当主(用户)线程结束时,JVM 会自动终止守护线程。

并发工具

Java 的 java.util.concurrent 包提供了高级构造,简化多线程编程。

ExecutorService

import java.util.concurrent.*;

public class MasteringBackend {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Callable task = () -> {
            Thread.sleep(500);
            return 42;
        };

        Future future = executor.submit(task);
        System.out.println("Result: " + future.get());

        executor.shutdown();
    }
}

CountDownLatch

import java.util.concurrent.*;

public class MasteringBackend {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        Runnable worker = () -> {
            System.out.println(Thread.currentThread().getName() + " working");
            latch.countDown();
        };

        for (int i = 0; i  queue = new ArrayBlockingQueue<>(5);

        Thread producer = new Thread(() -> {
            try {
                queue.put("Message");
                System.out.println("Produced message");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                String msg = queue.take();
                System.out.println("Consumed: " + msg);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

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

        producer.join();
        consumer.join();
    }
}

这些工具处理线程池、同步以及线程间的数据交换,减少了对低层 synchronized 块和手动线程管理的需求。

Back to Blog

相关文章

阅读更多 »