赞
踩
一、 前言
多线程是 Java 编程中一项重要的技术,它允许程序同时执行多个任务,从而提高程序效率和响应速度。本教程将带你从基础知识到高级应用,全面掌握 Java 多线程编程。
二、 基础知识
三、 创建和启动线程
1. 继承 Thread 类:
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程正在运行...");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
2. 实现 Runnable 接口:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程正在运行...");
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
}
}
四、 线程同步
1. synchronized 关键字:
public class Counter { private int count = 0; public synchronized void increment() { count++; } } public class MyThread extends Thread { private Counter counter; public MyThread(Counter counter) { this.counter = counter; } @Override public void run() { for (int i = 0; i < 1000; i++) { counter.increment(); } } public static void main(String[] args) { Counter counter = new Counter(); MyThread thread1 = new MyThread(counter); MyThread thread2 = new MyThread(counter); thread1.start(); thread2.start(); // 等待两个线程执行完毕 try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("count: " + counter.count); } }
2. ReentrantLock:
import java.util.concurrent.locks.ReentrantLock; public class Counter { private int count = 0; private ReentrantLock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } } // 其他代码与上面类似
五、 线程通信
1. wait() 和 notify() 方法:
public class ProducerConsumer { private Object lock = new Object(); private boolean hasData = false; private String data; public void produce(String data) { synchronized (lock) { while (hasData) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.data = data; hasData = true; lock.notify(); } } public String consume() { synchronized (lock) { while (!hasData) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } hasData = false; lock.notify(); return data; } } public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); Thread producer = new Thread(() -> { for (int i = 0; i < 10; i++) { pc.produce("数据" + i); } }); Thread consumer = new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("消费数据: " + pc.consume()); } }); producer.start(); consumer.start(); } }
2. BlockingQueue:
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumer { private BlockingQueue<String> queue = new LinkedBlockingQueue<>(); public void produce(String data) { try { queue.put(data); System.out.println("生产数据: " + data); } catch (InterruptedException e) { e.printStackTrace(); } } public String consume() { try { String data = queue.take(); System.out.println("消费数据: " + data); return data; } catch (InterruptedException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); Thread producer = new Thread(() -> { for (int i = 0; i < 10; i++) { pc.produce("数据" + i); } }); Thread consumer = new Thread(() -> { for (int i = 0; i < 10; i++) { pc.consume(); } }); producer.start(); consumer.start(); } }
3. Condition:
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class ProducerConsumer { private ReentrantLock lock = new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); private int count = 0; private int capacity = 10; public void produce(String data) { lock.lock(); try { while (count == capacity) { notFull.await(); } // 生产数据 count++; notEmpty.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public String consume() { lock.lock(); try { while (count == 0) { notEmpty.await(); } // 消费数据 count--; notFull.signal(); return "数据"; } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return null; } public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); Thread producer = new Thread(() -> { for (int i = 0; i < 10; i++) { pc.produce("数据" + i); } }); Thread consumer = new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("消费数据: " + pc.consume()); } }); producer.start(); consumer.start(); } }
六、 线程池
1. ThreadPoolExecutor:
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("线程正在执行任务..."); }); } // 关闭线程池 executor.shutdown(); } }
七、 线程安全类
八、 高级应用
九、 总结
Java 多线程编程是一项复杂但强大的技术,它可以提高程序效率、增强用户体验、提升资源利用率。本教程介绍了 Java 多线程编程的基础知识、线程同步、线程通信、线程池以及高级应用。希望这篇文章能帮助你更好地理解和应用 Java 多线程编程。
十、 练习
十一、 参考资料
最后,希望你能通过学习这篇文章,对 Java 多线程编程有一个更深入的了解,并在实际开发中灵活运用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。