使用Java编写并发问题案例
在Java中,并发问题通常涉及到线程的创建、同步机制的使用以及可能出现的竞争条件等问题。下面提供一个简单的Java并发问题案例——生产者消费者问题。
import java.util.concurrent.*;
// 生产者类
class Producer implements Runnable {
private final int capacity;
private producerLock lock;
public Producer(int capacity) {
this.capacity = capacity;
lock = new producerLock();
}
@Override
public void run() {
while (true) {
try {
// 生产
lock.acquire();
System.out.println("Producer produces: " + Math.random());
// 消费
lock.release();
System.out.println("Consumer consumes: " + Math.random());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
// 消费者类
class Consumer implements Runnable {
private final int capacity;
private consumerLock lock;
public Consumer(int capacity) {
this.capacity = capacity;
lock = new consumerLock();
}
@Override
public void run() {
while (true) {
try {
// 生产
lock.acquire();
System.out.println("Consumer consumes: " + Math.random());
// 消费
lock.release();
System.out.println("Producer produces: " + Math.random());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
// 信号量锁类
class producerLock implements Lock {
private final int capacity;
private AtomicInteger count;
public producerLock(int capacity) {
this.capacity = capacity;
count = new AtomicInteger(capacity);
}
@Override
public void lock() throws LockFailedException {
while (count.getAndDec() < 0) {
// 生产者数量超过容量,等待
try {
Thread.sleep(100); // 假设生产与消费的时间间隔为100ms
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
// 加锁成功,更新计数器
count.setAndIncrement();
}
@Override
public void unlock() throws UnlockFailedException {
// 减锁,如果当前计数为0,则表示其他线程已经获取了锁,解锁失败
if (count.decrementAndGet() < 0) {
throw new UnlockFailedException("Failed to unlock. Lock count is negative.");
}
}
@Override
public boolean tryLock() throws锁定失败异常 {
// 同理,尝试加锁,如果当前计数为0,则表示其他线程已经获取了锁,尝试加锁失败
if (count.incrementAndGet() > capacity) {
throw new UnlockFailedException("Failed to lock. Lock count is greater than the capacity.");
}
return true;
}
@Override
public void lockInterruptibly() throws InterruptedException, 无法锁定异常 {
tryLock();
if (Thread.currentThread().isInterrupted()) {
unlock();
throw new InterruptedException("Interrupted while waiting to lock.");
}
}
@Override
public boolean tryLockInterruptibly() throws InterruptedException, 无法锁定异常 {
return tryLock();
if (Thread.currentThread().isInterrupted()) {
unlock();
throw new InterruptedException("Interrupted while waiting to lock.");
}
}
}
以上代码创建了一个生产者和消费者模型,每个类都实现了一个Runnable
接口,通过线程来模拟生产和消费的过程。在锁的使用上,我们采用了信号量的方式,保证了多线程环境下的同步问题。
还没有评论,来说两句吧...