zoukankan      html  css  js  c++  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();
    		}
    	}
    }
    
  • 相关阅读:
    [贪心经典算法]Kruskal算法
    [经典贪心算法]Prim算法
    Java容器之List接口
    Java容器之Set接口
    JDK中的泛型
    Java中ArrayList与数组间相互转换
    Java中的增强for循环
    Java容器之Iterator接口
    Java之容器
    eg_4
  • 原文地址:https://www.cnblogs.com/denggelin/p/6346233.html
Copyright © 2011-2022 走看看