Java多线程编程与并发控制策略
大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天,我想和大家分享一下Java多线程编程与并发控制策略的相关知识,希望对大家有所帮助。
一、Java多线程编程基础
1.1 线程的创建与启动
在Java中,线程可以通过继承Thread
类或实现Runnable
接口来创建和启动。
// 继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
// 实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.start();
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}
1.2 线程的生命周期
线程在Java中的生命周期包括以下几个阶段:
- 新建(New):线程对象被创建,但尚未调用
start()
方法。 - 就绪(Runnable):
start()
方法被调用,线程进入就绪状态,等待CPU调度。 - 运行(Running):线程获得CPU资源,开始执行
run()
方法。 - 阻塞(Blocked):线程因某些原因(如等待I/O操作)进入阻塞状态。
- 终止(Terminated):线程执行完
run()
方法或因异常退出。
二、并发控制策略
2.1 同步(Synchronized)
Synchronized
关键字用于保证多个线程访问共享资源时的互斥性,防止数据不一致问题。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + counter.getCount());
}
}
2.2 显式锁(Explicit Lock)
ReentrantLock
是Java中的显式锁,提供了比Synchronized
更灵活的锁机制。
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
2.3 信号量(Semaphore)
Semaphore
用于控制同时访问某个特定资源的线程数量。
import java.util.concurrent.Semaphore;
class Resource {
private final Semaphore semaphore = new Semaphore(3);
public void use() {
try {
semaphore.acquire();
System.out.println("Resource in use by " + Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
public class Main {
public static void main(String[] args) {
Resource resource = new Resource();
for (int i = 0; i < 10; i++) {
new Thread(resource::use).start();
}
}
}
2.4 读写锁(ReadWriteLock)
ReadWriteLock
允许多个读操作同时进行,但写操作独占。
import java.util.concurrent.locks.ReentrantReadWriteLock;
class SharedData {
private int data = 0;
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
public void write(int value) {
rwLock.writeLock().lock();
try {
data = value;
} finally {
rwLock.writeLock().unlock();
}
}
public int read() {
rwLock.readLock().lock();
try {
return data;
} finally {
rwLock.readLock().unlock();
}
}
}
三、并发工具类
3.1 CountDownLatch
CountDownLatch
用于让一个或多个线程等待其他线程完成操作。
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is working");
latch.countDown();
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads have finished");
}
}
3.2 CyclicBarrier
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(() -> {
System.out.println(Thread.currentThread().getName() + " is working");
try {
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
总结
Java多线程编程与并发控制是一个复杂而重要的领域。在实际开发中,我们需要根据具体需求选择合适的并发控制策略,确保程序的正确性和性能。通过学习和掌握这些技巧,我们可以更好地应对多线程编程中的各种挑战,为用户提供高效、可靠的应用程序。