66.Java-资源抢夺案例(使用Lock)

  • 调用类
package com.test.thread_Lock;

public class MainClass {
    
    public static void main(String[] args) {
        
        Resource resource = new Resource();
        
        new Thread(new Businesser(resource)).start();
        new Thread(new Visitor(resource)).start();
    }   
    
}
  • 资源类
package com.test.thread_Lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Resource {
    
    private String name;
    private String sex;
    
    private boolean isEmpty = true;
    private final Lock lock = new ReentrantLock();
    private Condition con = lock.newCondition();
    
    public void setterData(String name,String sex) {
        
        lock.lock();
        try {
            
            while(!isEmpty) {
                con.await();
            }
            
            this.name = name;
            this.sex = sex;
            
            isEmpty = false;
            con.signalAll();
            
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            
            lock.unlock();
            
        }
        
    }
    
    public void getterData() {
        lock.lock();
        
        try {
            while(isEmpty) {
                con.await();
            }
            
            System.out.println(this.name+":"+this.sex);
            
            isEmpty = true;
            con.signalAll();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            
            
            lock.unlock();
        }
        

    }
}

  • 商家
package com.test.thread_Lock;

public class Businesser implements Runnable{
    private Resource resource = null;
    
    public Businesser(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        for (int i = 0; i < 50; i++) {
            
            this.resource.setterData("尼古拉斯"+i+"世", "男");
            
        }
    }
}

  • 客人
package com.test.thread_Lock;

import java.lang.Runnable;
public class Visitor implements Runnable{
    private Resource resource = null;
    
    public Visitor(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        for (int i = 0; i < 50; i++) {
            
            this.resource.getterData();;
            
        }
    }
}

你可能感兴趣的:(66.Java-资源抢夺案例(使用Lock))