说明
ReentrantLock是java官方的一个线程锁类,ReentarntLock实现了Lock的接口
我们只需要使用这个,就可以不用使用synchronized同步关键字以及对应的notifyall方法和wait方法去写我们的生产者消费者模式。
这样就可以大大简化我们的代码
代码
Producer.java
package producterandcustomer;
import java.util.List;
import java.util.concurrent.locks.Lock;
/**
* @author StarsOne
* @date Create in 2019-4-13 0013 14:51:21
* @description
*/
class Producter extends Thread {
List<Object> warehouse;
private String name;
Lock lock;
public Producter(List<Object> warehouse, String name, Lock lock) {
this.warehouse = warehouse;
this.name = "生产者" + name;
//多态,ReentarntLock实现了Lock的接口,所以可以传进来
this.lock = lock;
}
@Override
public void run() {
while (true) {
//加锁
lock.lock();
try {
if (warehouse.size() < 10) {
warehouse.add(new Object());
System.out.println(name + "生产1件" + "当前仓库有" + warehouse.size() + "件");
}
} finally {
//解锁
lock.unlock();
}
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Consumer.java
package producterandcustomer;
import java.util.List;
import java.util.concurrent.locks.Lock;
/**
* @author StarsOne
* @date Create in 2019-4-13 0013 14:51:21
* @description
*/
class Cuotmer extends Thread{
List<Object> warehouse;
private String name;
Lock lock;
public Cuotmer(List<Object> warehouse, String name, Lock lock) {
this.warehouse = warehouse;
this.name = "消费者"+name;
this.lock = lock;
}
@Override
public void run() {
while (true) {
//加锁
lock.lock();
try {
if (warehouse.size() > 0) {
warehouse.remove(0);
System.out.println(name+"消费1件"+"当前仓库有"+warehouse.size()+"件");
}
}finally {
//最后释放
lock.unlock();
}
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Test.java
package producterandcustomer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author StarsOne
* @date Create in 2019-4-13 0013 14:57:26
* @description
*/
class Test {
public static void main(String[] args) {
List<Object> warehouse = new ArrayList<>();
Lock lock = new ReentrantLock();
new Cuotmer(warehouse, "小米", lock).start();
new Cuotmer(warehouse, "小蓝", lock).start();
new Cuotmer(warehouse, "小浩", lock).start();
new Cuotmer(warehouse, "小家", lock).start();
new Cuotmer(warehouse, "小留", lock).start();
new Producter(warehouse, "小一", lock).start();
new Producter(warehouse, "小二", lock).start();
new Producter(warehouse, "小香", lock).start();
new Producter(warehouse, "小叫", lock).start();
new Producter(warehouse, "小三", lock).start();
}
}