首页 > 其他 > 详细

Lock接口

时间:2017-01-24 07:42:31      阅读:229      评论:0      收藏:0      [点我收藏+]

 

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

 

Lock接口

原文:http://www.cnblogs.com/denggelin/p/6346233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!