Java作为一门广泛应用于企业级应用开发的编程语言,其并发编程能力一直备受关注。线程是Java并发编程的核心,本文将从JDK5开始,深入解析Java线程的原理、使用方法以及实战案例分析。
一、JDK5线程新特性
1. 可重入锁ReentrantLock
在JDK5之前,Java提供了synchronized关键字实现同步,但synchronized是一种重量级的锁。JDK5引入了可重入锁ReentrantLock,它提供了与synchronized相同的功能,但具有更高的灵活性和更好的性能。
public class ReentrantLockDemo {
private final ReentrantLock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
// ...执行业务逻辑
} finally {
lock.unlock();
}
}
}
2. 线程局部变量ThreadLocal
ThreadLocal为线程提供了局部变量,使得每个线程都拥有独立的变量副本,避免了线程之间的数据共享。
public class ThreadLocalDemo {
private static final ThreadLocal<String> threadLocal = new ThreadLocal<String>() {
@Override
protected String initialValue() {
return "Hello, " + Thread.currentThread().getName();
}
};
public static void main(String[] args) {
System.out.println(threadLocal.get());
}
}
3. 线程池ExecutorService
线程池是Java并发编程中的重要工具,它可以提高程序的性能,减少创建线程的开销。
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
executor.shutdown();
}
}
二、Java线程使用方法
1. 继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
// ...执行业务逻辑
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2. 实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
// ...执行业务逻辑
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
3. 使用线程池
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
executor.shutdown();
}
}
三、实战案例分析
1. 生产者-消费者模式
public class ProducerConsumerDemo {
private final Object lock = new Object();
private int count = 0;
public void produce() throws InterruptedException {
synchronized (lock) {
while (count > 0) {
lock.wait();
}
count++;
System.out.println("生产者生产,count=" + count);
lock.notifyAll();
}
}
public void consume() throws InterruptedException {
synchronized (lock) {
while (count <= 0) {
lock.wait();
}
count--;
System.out.println("消费者消费,count=" + count);
lock.notifyAll();
}
}
}
2. 线程安全队列
public class ConcurrentLinkedQueueDemo {
private final ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
public void add(int value) {
queue.add(value);
}
public int remove() {
return queue.poll();
}
}
四、总结
本文从JDK5线程新特性、Java线程使用方法以及实战案例分析等方面,深入解析了Java线程的相关知识。通过学习本文,相信读者能够更好地理解和应用Java线程,提高程序的性能和稳定性。
