欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java Lock接口详解及实例代码

程序员文章站 2024-03-08 13:41:16
java  lock接口 java.util.concurrent.locks 接口lock public interface loce loce实现提供...

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();
    }
  }
}

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