当前位置: 移动技术网 > IT编程>开发语言>Java > java Lock接口详解及实例代码

java Lock接口详解及实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

java  lock接口

java.util.concurrent.locks

接口lock

public interface loce

loce实现提供了比使用synchronized方法和语句可获得的更广泛的锁定操作


import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;
 
public class integerdemo {
  public static void main(string[] args) {
    // 创建3个线程对象
    sellticket st = new sellticket();
 
    thread t1 = new thread(st, "窗口1");
    thread t2 = new thread(st, "窗口2");
    thread t3 = new thread(st, "窗口3");
 
    // 启动线程
    t1.start();
    t2.start();
    t3.start();
  }
}
 
class sellticket implements runnable {
  private int ticket = 100;
  private lock lock = new reentrantlock();
 
  public void run() {
    while (true) {
      lock.lock();
 
      if (ticket > 0) {
        try {
          thread.sleep(100);
        } catch (interruptedexception e) {
          // todo auto-generated catch block
          e.printstacktrace();
        }
 
        system.out.println(thread.currentthread().getname() + "正在出售第" + (ticket--) + "张票。");
      }
 
      lock.unlock();
    }
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网