java Lock接口 java Lock接口详解及实例代码
人气:0想了解java Lock接口详解及实例代码的相关内容吗,在本文为您仔细讲解java Lock接口的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,Lock接口,java,Lock接口详解,java,Lock接口实例代码,下面大家一起来学习吧。
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(); } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
加载全部内容