Java 从入门到精通(续集20)——多线程编程
Java 中的多线程编程是指通过使用 Java 提供的各种多线程 API 和机制来实现多个线程之间的并发执行。Java 中主要使用的多线程技术包括 Thread、Runnable、Executor、ThreadPool、Lock、Semaphore、CountDownLatch 等。
一、Thread 和 Runnable
Java 中的 Thread 和 Runnable 是最基本的多线程 API,可以通过继承 Thread 类或实现 Runnable 接口来创建多个线程。
示例代码:
class MyThread extends Thread {public void run() {System.out.println("Thread " + Thread.currentThread().getId() + " is running.");}
}class MyRunnable implements Runnable {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();MyRunnable runnable = new MyRunnable();Thread thread3 = new Thread(runnable);Thread thread4 = new Thread(runnable);thread3.start();thread4.start();
}
二、Executor 和 ThreadPool
Java 中的 Executor 和 ThreadPool 是一种更高层次的多线程机制,可以通过 ExecutorService 来管理线程池和任务队列,从而实现更加灵活和高效的线程处理。
示例代码:
class MyTask implements Runnable {public void run() {System.out.println("Task " + Thread.currentThread().getId() + " is running.");}
}public static void main(String[] args) {ExecutorService executor = Executors.newFixedThreadPool(2);for (int i = 0; i < 10; i++) {executor.execute(new MyTask());}executor.shutdown();while (!executor.isTerminated()) {Thread.yield();}System.out.println("All tasks are finished.");
}
三、Lock 和 Condition
Java 中的 Lock 和 Condition 是一种更加灵活和高度封装的多线程机制,可以通过 ReentrantLock 和 Condition 来实现更精细的线程同步和通信操作。
示例代码:
class MyQueue {private Lock lock = new ReentrantLock();private Condition full = lock.newCondition();private Condition empty = lock.newCondition();private Queue<String> queue = new LinkedList<>();private int maxSize = 10;public void put(String item) throws InterruptedException {try {lock.lock();while (queue.size() == maxSize) {full.await();}queue.offer(item);empty.signalAll();} finally {lock.unlock();}}public String take() throws InterruptedException {try {lock.lock();while (queue.isEmpty()) {empty.await();}String item = queue.poll();full.signalAll();return item;} finally {lock.unlock();}}
}public static void main(String[] args) {MyQueue queue = new MyQueue();new Thread(() -> {for (int i = 0; i < 20; i++) {try {queue.put("item-" + i);System.out.println("put item-" + i);Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}).start();new Thread(() -> {for (int i = 0; i < 20; i++) {try {String item = queue.take();System.out.println("take " + item);Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}).start();
}
以上就是 Java 中的多线程编程,通过使用 Thread、Runnable、Executor、ThreadPool、Lock、Condition 等机制可以实现更加灵活和高效的多线程操作。在实际开发中,要注意同步和通信等问题,并尽可能地使用线程池、锁、信号量、闭锁等技术来提高性能和可靠性。下一篇续集将为您介绍 Java 中的反射和注解。