1、将ShareData类中的变量,采用面向对象的方式封装起来
2、生产者和消费者类中构造方法接收ShareData类对象,之后再run方法中进行
3、创建生产者和消费者线程对象,构造方法中传入ShareData类对象
4、开启两个线程
代码实现
ShareData类
public class ShareDataLock {
private static boolean flag = false;
static final ReentrantLock reentrantLock= new ReentrantLock();
public static boolean isFlag() {
return flag;
}
public static void setFlag(boolean flag) {
ShareDataLock.flag = flag;
}
}
生产者
public class ProducerLock extends Thread{
@Override
public void run() {
while (true){
ShareDataLock.reentrantLock.lock();
if (!ShareDataLock.isFlag()){
product();
ShareDataLock.setFlag(true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ShareDataLock.reentrantLock.unlock();
}
}
public void product(){
System.out.println("生产了一个商品");
}
}
消费者
public class ConsumerLock extends Thread{
@Override
public void run() {
while (true){
ShareDataLock.reentrantLock.lock();
if (ShareDataLock.isFlag()){
product();
ShareDataLock.setFlag(false);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ShareDataLock.reentrantLock.unlock();
}
}
public void product(){
System.out.println("消费了一个商品");
}
}
main方法开启线程
public class Main {
public static void main(String[] args) {
new ConsumerLock().start();
new ProducerLock().start();
}
}
效果