标签:对象 cep import tran 窗口 private class break stat
package threadT; public class ThreadMain { public static void main(String args[]) { SellTicket str = new SellTicket(10); Thread tr1 = new Thread(str, "窗口1"); Thread tr2 = new Thread(str, "窗口2"); Thread tr3 = new Thread(str, "窗口3"); tr1.start(); tr2.start(); tr3.start(); } }
package threadT; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SellTicket implements Runnable { // 定义票的数量 private int tickets = 0; public SellTicket(int count) { tickets = count; } // 定义锁对象 private final Lock lock = new ReentrantLock(); public void run() { // 卖完标记 boolean over = false; while (true) { try { if (tickets == 0) { System.out.println(Thread.currentThread().getName() + "检测到已售完"); over = true; break; } // 加锁 lock.lock(); if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票"); } } finally { if (!over) // 释放锁 lock.unlock(); } } } }
标签:对象 cep import tran 窗口 private class break stat
原文地址:https://www.cnblogs.com/wujf/p/9090124.html