java并发的知识点有哪些

发布时间:2022-01-06 15:28:31 作者:iii
来源:亿速云 阅读:122

Java并发的知识点有哪些

目录

  1. 引言
  2. 线程基础
  3. 线程同步
  4. 线程通信
  5. 线程池
  6. 并发集合
  7. 并发工具类
  8. Fork/Join框架
  9. CompletableFuture
  10. 总结

引言

Java并发编程是Java编程中的一个重要领域,涉及到多线程、线程同步、线程通信、线程池、并发集合、并发工具类等多个方面。掌握Java并发编程的知识点,可以帮助开发者编写高效、安全的多线程程序。本文将详细介绍Java并发编程中的各个知识点,帮助读者全面理解Java并发编程的核心概念和技术。

线程基础

线程的创建

在Java中,创建线程有两种主要方式:

  1. 继承Thread类:通过继承Thread类并重写run()方法来创建线程。 “`java class MyThread extends Thread { @Override public void run() { System.out.println(“Thread is running”); } }

public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }


2. **实现Runnable接口**:通过实现`Runnable`接口并将其传递给`Thread`类的构造函数来创建线程。
   ```java
   class MyRunnable implements Runnable {
       @Override
       public void run() {
           System.out.println("Thread is running");
       }
   }

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

线程的生命周期

线程的生命周期包括以下几个状态:

  1. 新建(New):线程对象被创建,但尚未启动。
  2. 就绪(Runnable):线程已经启动,等待CPU调度执行。
  3. 运行(Running):线程正在执行run()方法中的代码。
  4. 阻塞(Blocked):线程因为某些原因(如等待锁、I/O操作等)暂时停止执行。
  5. 终止(Terminated):线程执行完毕或被强制终止。

线程的优先级

Java中的线程优先级分为1(最低)到10(最高),默认优先级为5。可以通过setPriority()方法设置线程的优先级。

Thread thread = new Thread(() -> System.out.println("Thread is running"));
thread.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级
thread.start();

线程的调度

线程的调度由JVM和操作系统共同决定,开发者无法直接控制线程的调度顺序。可以通过yield()方法让当前线程让出CPU资源,进入就绪状态。

Thread.yield(); // 让出CPU资源

线程同步

synchronized关键字

synchronized关键字用于实现线程同步,确保同一时刻只有一个线程可以访问被synchronized修饰的代码块或方法。

class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

volatile关键字

volatile关键字用于确保变量的可见性,即当一个线程修改了volatile变量的值,其他线程可以立即看到修改后的值。

class SharedObject {
    private volatile boolean flag = false;

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public boolean isFlag() {
        return flag;
    }
}

锁机制

Java提供了ReentrantLock类来实现更灵活的锁机制。与synchronized相比,ReentrantLock提供了更多的功能,如可中断锁、公平锁等。

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Counter {
    private int count = 0;
    private Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }
}

原子类

Java提供了AtomicIntegerAtomicLong等原子类,用于实现无锁的线程安全操作。

import java.util.concurrent.atomic.AtomicInteger;

class Counter {
    private AtomicInteger count = new AtomicInteger(0);

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

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

线程通信

wait/notify机制

wait()notify()方法用于实现线程之间的通信。wait()方法使当前线程进入等待状态,直到其他线程调用notify()notifyAll()方法唤醒它。

class SharedResource {
    private boolean isReady = false;

    public synchronized void waitForReady() throws InterruptedException {
        while (!isReady) {
            wait();
        }
    }

    public synchronized void setReady() {
        isReady = true;
        notifyAll();
    }
}

Condition接口

Condition接口提供了更灵活的线程通信机制,可以与ReentrantLock配合使用。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharedResource {
    private boolean isReady = false;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void waitForReady() throws InterruptedException {
        lock.lock();
        try {
            while (!isReady) {
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }

    public void setReady() {
        lock.lock();
        try {
            isReady = true;
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

BlockingQueue

BlockingQueue是一个线程安全的队列,支持阻塞的插入和移除操作。

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

        // 生产者线程
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    queue.put(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 消费者线程
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    int value = queue.take();
                    System.out.println("Consumed: " + value);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

线程池

线程池的创建

Java提供了Executors工厂类来创建不同类型的线程池。

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

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

        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                System.out.println("Thread is running");
            });
        }

        executor.shutdown();
    }
}

线程池的参数

线程池的核心参数包括:

线程池的执行流程

  1. 当有新任务提交时,线程池首先检查核心线程数是否已满,如果未满则创建新线程执行任务。
  2. 如果核心线程数已满,则将任务放入任务队列。
  3. 如果任务队列已满,则检查最大线程数是否已满,如果未满则创建新线程执行任务。
  4. 如果最大线程数已满,则根据拒绝策略处理任务。

线程池的关闭

线程池可以通过shutdown()方法优雅地关闭,等待所有任务执行完毕后再关闭线程池。

executor.shutdown();

并发集合

ConcurrentHashMap

ConcurrentHashMap是线程安全的哈希表,支持高并发的读写操作。

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("key1", 1);
        map.put("key2", 2);

        System.out.println(map.get("key1"));
    }
}

CopyOnWriteArrayList

CopyOnWriteArrayList是线程安全的列表,适用于读多写少的场景。

import java.util.concurrent.CopyOnWriteArrayList;

public class Main {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        list.add("item1");
        list.add("item2");

        System.out.println(list.get(0));
    }
}

BlockingQueue

BlockingQueue是一个线程安全的队列,支持阻塞的插入和移除操作。

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

        // 生产者线程
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    queue.put(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 消费者线程
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    int value = queue.take();
                    System.out.println("Consumed: " + value);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

并发工具类

CountDownLatch

CountDownLatch用于等待多个线程完成任务后再继续执行。

import java.util.concurrent.CountDownLatch;

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

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println("Thread is running");
                latch.countDown();
            }).start();
        }

        latch.await();
        System.out.println("All threads have finished");
    }
}

CyclicBarrier

CyclicBarrier用于等待多个线程到达某个屏障点后再继续执行。

import java.util.concurrent.CyclicBarrier;

public class Main {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3, () -> {
            System.out.println("All threads have reached the barrier");
        });

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    System.out.println("Thread is running");
                    barrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

Semaphore

Semaphore用于控制同时访问某个资源的线程数量。

import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("Thread is running");
                    Thread.sleep(1000);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

Exchanger

Exchanger用于在两个线程之间交换数据。

import java.util.concurrent.Exchanger;

public class Main {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> {
            try {
                String data = "Data from Thread 1";
                System.out.println("Thread 1 is sending: " + data);
                String received = exchanger.exchange(data);
                System.out.println("Thread 1 received: " + received);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                String data = "Data from Thread 2";
                System.out.println("Thread 2 is sending: " + data);
                String received = exchanger.exchange(data);
                System.out.println("Thread 2 received: " + received);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

Fork/Join框架

Fork/Join的基本概念

Fork/Join框架是Java 7引入的并行计算框架,适用于将大任务拆分为多个小任务并行执行的场景。

Fork/Join的使用

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;

class SumTask extends RecursiveTask<Long> {
    private final long[] numbers;
    private final int start;
    private final int end;

    public SumTask(long[] numbers, int start, int end) {
        this.numbers = numbers;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        int length = end - start;
        if (length <= 1000) {
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += numbers[i];
            }
            return sum;
        } else {
            int mid = start + length / 2;
            SumTask leftTask = new SumTask(numbers, start, mid);
            SumTask rightTask = new SumTask(numbers, mid, end);
            leftTask.fork();
            long rightResult = rightTask.compute();
            long leftResult = leftTask.join();
            return leftResult + rightResult;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        long[] numbers = new long[10000];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = i + 1;
        }

        ForkJoinPool pool = new ForkJoinPool();
        long result = pool.invoke(new SumTask(numbers, 0, numbers.length));
        System.out.println("Sum: " + result);
    }
}

CompletableFuture

CompletableFuture的基本概念

CompletableFuture是Java 8引入的异步编程工具,用于处理异步任务的结果。

CompletableFuture的使用

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, World!";
        });

        future.thenAccept(System.out::println);

        String result = future.get();
        System.out.println("Result: " + result);
    }
}

总结

Java并发编程涉及的知识点非常广泛,包括线程的创建与生命周期、线程同步与通信、线程池、并发集合、并发工具类、Fork/Join框架以及CompletableFuture等。掌握这些知识点,可以帮助开发者编写高效、安全的多线程程序。希望本文能够帮助读者全面理解Java并发编程的核心概念和技术,并在实际开发中灵活运用。

推荐阅读:
  1. VsVim的知识点有哪些
  2. Java并发问题有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:java线程状态的种类有哪些

下一篇:采用ThinSOT封装的低损耗PowerPathTM控制器LTC4412怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》