zoukankan      html  css  js  c++  java
  • LockDemo 锁对象

    class Resource {
    private boolean flag = false;
    private String name;
    private int count;
    //资源锁
    Lock lock = new ReentrantLock();
    //监视器类
    Condition produce_con = lock.newCondition();
    Condition customer_con = lock.newCondition();


    public void set(String name){
    //获取锁
    lock.lock();
    try{
    while(flag)
    //生产者线程等待
    try{produce_con.await();}catch(Exception e){}
    //直接唤醒消费者线程
    customer_con.signal();
    flag = true;
    count++;
    this.name = name;
    System.out.println(this.name+" "+this.count);
    }
    finally{
    //释放锁,不管try中代码是否报错,记得释放锁。
    lock.unlock();
    }

    }

    public void get(){
    //获取锁
    lock.lock();
    try{
    while(!flag)
    //消费者线程等待
    try{customer_con.await();}catch(Exception e){}
    //直接唤醒生产者线程
    produce_con.signal();
    flag = false;
    System.out.println(this.name+" customer"+this.count);
    }
    finally{
    //释放锁资源
    lock.unlock();
    }

    }


    }
    class Producer implements Runnable{
    Resource s;
    private Producer(){};

    Producer(Resource t){
    this.s = t;
    }
    public void run(){
    int i = 0;
    while(true){
    if(i ==0)
    s.set("rastduck");
    else
    s.set("car");
    i = (i+1) %2;
    }
    }
    }
    class Customer implements Runnable{

    Resource s;
    private Customer(){}
    Customer(Resource t){
    this.s = t;
    }
    public void run(){
    while(true){
    s.get();
    }
    }

    }

    class LockDemo{
    public static void main (String[] arg){
    Resource s = new Resource();

    Customer c = new Customer(s);
    Producer p = new Producer(s);
    Thread t1 = new Thread(c);
    Thread t2 = new Thread(c);
    Thread t3 = new Thread(p);
    Thread t4 = new Thread(p);

    t1.start();
    t2.start();
    t3.start();
    t4.start();

    }
    }

    每一步都是一个深刻的脚印
  • 相关阅读:
    TCP建立连接和断开连接
    城市三级联动Springmvc+mysql
    JS页面间数据传递的各种方法
    点击Button弹出登陆注册框
    一个多表联合查询引发的思考
    Linq扩展方法获取单个元素
    Visual Studio 常见问题
    格式化asp.net mvc视图页面
    2014上半年度挑战回顾
    2014年上半度年度挑战
  • 原文地址:https://www.cnblogs.com/chzlh/p/9371541.html
Copyright © 2011-2022 走看看