您好,登录后才能下订单哦!
Java并发编程是Java编程中的一个重要领域,涉及到多线程、线程同步、线程通信、线程池、并发集合、并发工具类等多个方面。掌握Java并发编程的知识点,可以帮助开发者编写高效、安全的多线程程序。本文将详细介绍Java并发编程中的各个知识点,帮助读者全面理解Java并发编程的核心概念和技术。
在Java中,创建线程有两种主要方式:
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();
       }
   }
线程的生命周期包括以下几个状态:
run()方法中的代码。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修饰的代码块或方法。
class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
}
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提供了AtomicInteger、AtomicLong等原子类,用于实现无锁的线程安全操作。
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()或notifyAll()方法唤醒它。
class SharedResource {
    private boolean isReady = false;
    public synchronized void waitForReady() throws InterruptedException {
        while (!isReady) {
            wait();
        }
    }
    public synchronized void setReady() {
        isReady = true;
        notifyAll();
    }
}
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是一个线程安全的队列,支持阻塞的插入和移除操作。
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();
    }
}
线程池的核心参数包括:
线程池可以通过shutdown()方法优雅地关闭,等待所有任务执行完毕后再关闭线程池。
executor.shutdown();
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是线程安全的列表,适用于读多写少的场景。
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是一个线程安全的队列,支持阻塞的插入和移除操作。
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用于等待多个线程完成任务后再继续执行。
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用于等待多个线程到达某个屏障点后再继续执行。
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用于控制同时访问某个资源的线程数量。
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用于在两个线程之间交换数据。
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框架是Java 7引入的并行计算框架,适用于将大任务拆分为多个小任务并行执行的场景。
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是Java 8引入的异步编程工具,用于处理异步任务的结果。
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并发编程的核心概念和技术,并在实际开发中灵活运用。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。