多線程模擬生產者消費者示例之Lock
阿新 • • 發佈:2018-09-30
ger condition read image 技術分享 封裝 start art .get
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>(1);
LockEntity lockEntity = new LockEntity();
new Thread(new PThread(list, lockEntity)).start();
new Thread(new CThread(list, lockEntity)).start();
}
}
/**
* 生產者
*/
class PThread implements Runnable {
private List<String> list;
private LockEntity lockEntity;
private AtomicInteger integer = new AtomicInteger();
public PThread(List<String> list, LockEntity lockEntity) {
this.list = list;
this.lockEntity = lockEntity;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
//上鎖
lockEntity.lock.lock();
if (lockEntity.flag) {
String data = integer.getAndIncrement() + "";
list.add(data);
System.out.println("生產者線程,生產一個數據:" + data);
lockEntity.flag = false;
lockEntity.condition.signal(); //喚醒
} else {
lockEntity.condition.await(); //等待
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lockEntity.lock.unlock();
}
}
}
}
class CThread implements Runnable {
private List<String> list;
private LockEntity lockEntity;
public CThread(List<String> list, LockEntity lockEntity) {
this.list = list;
this.lockEntity = lockEntity;
}
@Override
public void run() {
while (true) {
try {
lockEntity.lock.lock();
if (!lockEntity.flag) {
String data = list.remove(0);
System.out.println("消費者線程,消費了一個數據:" + data);
lockEntity.flag = true;
lockEntity.condition.signal();
} else {
lockEntity.condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lockEntity.lock.unlock();
}
}
}
}
/**
* 封裝鎖等信息
*/
class LockEntity {
public boolean flag = true;
public Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
}
多線程模擬生產者消費者示例之Lock