使用Java实现高并发编程

使用Java实现高并发编程

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天我们来讨论Java中的高并发编程。Java提供了丰富的并发编程工具和框架,包括线程、线程池、并发集合和锁机制等。本文将通过代码示例详细介绍如何使用这些工具实现高并发编程。

1. 线程的创建与管理

Java中创建线程的方式主要有两种:继承Thread类和实现Runnable接口。

继承Thread类

package cn.juwatech.concurrency;

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread " + Thread.currentThread().getId() + " is running");
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        thread1.start();
        thread2.start();
    }
}

实现Runnable接口

package cn.juwatech.concurrency;

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread " + Thread.currentThread().getId() + " is running");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());
        thread1.start();
        thread2.start();
    }
}

2. 线程池

线程池通过重用线程来提高性能,避免频繁创建和销毁线程。Java的Executor框架提供了多种线程池实现。

package cn.juwatech.concurrency;

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

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                System.out.println("Thread " + Thread.currentThread().getId() + " is running");
            });
        }
        executor.shutdown();
    }
}

3. 并发集合

Java提供了线程安全的并发集合,如ConcurrentHashMap、CopyOnWriteArrayList等,适用于高并发场景。

ConcurrentHashMap

package cn.juwatech.concurrency;

import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
        concurrentMap.put("A", 1);
        concurrentMap.put("B", 2);
        concurrentMap.put("C", 3);

        concurrentMap.forEach((key, value) -> {
            System.out.println("Key: " + key + ", Value: " + value);
        });
    }
}

CopyOnWriteArrayList

package cn.juwatech.concurrency;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListExample {
    public static void main(String[] args) {
        List<String> list = new CopyOnWriteArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");

        list.forEach(item -> {
            System.out.println("Item: " + item);
        });
    }
}

4. 锁机制

Java提供了多种锁机制以确保线程安全,包括synchronized关键字、ReentrantLock和读写锁等。

synchronized关键字

package cn.juwatech.concurrency;

public class SynchronizedExample {
    private int count = 0;

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

    public static void main(String[] args) {
        SynchronizedExample example = new SynchronizedExample();

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

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count: " + example.count);
    }
}

ReentrantLock

package cn.juwatech.concurrency;

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

public class ReentrantLockExample {
    private int count = 0;
    private final Lock lock = new ReentrantLock();

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

    public static void main(String[] args) {
        ReentrantLockExample example = new ReentrantLockExample();

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

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count: " + example.count);
    }
}

读写锁

读写锁允许多个线程同时读,但只允许一个线程写,从而提高并发性能。

package cn.juwatech.concurrency;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReadWriteLock;

public class ReadWriteLockExample {
    private int count = 0;
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();

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

    public int getCount() {
        rwLock.readLock().lock();
        try {
            return count;
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockExample example = new ReadWriteLockExample();

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

        Runnable readTask = () -> {
            for (int i = 0; i < 1000; i++) {
                System.out.println("Count: " + example.getCount());
            }
        };

        Thread writer = new Thread(writeTask);
        Thread reader = new Thread(readTask);

        writer.start();
        reader.start();

        try {
            writer.join();
            reader.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

5. 并发工具类

Java还提供了一些便捷的并发工具类,如CountDownLatch、CyclicBarrier和Semaphore等。

CountDownLatch

CountDownLatch允许一个或多个线程等待其他线程完成操作。

package cn.juwatech.concurrency;

import java.util.concurrent.CountDownLatch;

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

        Runnable task = () -> {
            System.out.println("Thread " + Thread.currentThread().getId() + " is running");
            latch.countDown();
        };

        for (int i = 0; i < threadCount; i++) {
            new Thread(task).start();
        }

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

CyclicBarrier

CyclicBarrier允许一组线程相互等待,直到到达一个共同的屏障点。

package cn.juwatech.concurrency;

import java.util.concurrent.CyclicBarrier;

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

        Runnable task = () -> {
            try {
                System.out.println("Thread " + Thread.currentThread().getId() + " is waiting at the barrier");
                barrier.await();
                System.out.println("Thread " + Thread.currentThread().getId() + " has crossed the barrier");
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < threadCount; i++) {
            new Thread(task).start();
        }
    }
}

Semaphore

Semaphore用于控制对资源的访问,允许多个线程同时访问特定数量的资源。

package cn.juwatech.concurrency;

import java.util.concurrent.Semaphore;

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

        Runnable task = () -> {
            try {
                semaphore.acquire();
                System.out.println("Thread " + Thread.currentThread().getId() + " is accessing the resource");
                Thread.sleep(1000); // 模拟资源访问
                semaphore.release();
                System.out.println("Thread "

 + Thread.currentThread().getId() + " has released the resource");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread(task).start();
        }
    }
}

通过以上内容,我们详细介绍了Java中高并发编程的基本概念及其实现方法,包括线程、线程池、并发集合、锁机制和并发工具类的使用。通过这些示例代码,大家可以更好地理解和应用Java的并发编程技术。

著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

posted @ 2024-07-15 09:53  省赚客开发者团队  阅读(1)  评论(0编辑  收藏  举报