public class SellTicket02 implements Runnable {
private int tickets = 100;
private Lock lock=new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}finally {
lock.unlock();
}
}
}
}
-------------------------------------------------------------------------------------------------------------------
public class SellTicket implements Runnable {
// private int tickets = 100;
private static int tickets = 100;
//private Object obj=new Object();
private int x=0;
@Override
public void run() {
while (true) {
if(x%2==0){
// synchronized (this){
synchronized (SellTicket.class){
if (tickets > 0) {
//通过sleep模拟出票时间
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}else {
sellTic();
}
x++;
}
}
// private synchronized void sellTic() {
private static synchronized void sellTic() {
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
-----------------------------------------------------------------------------------------------------------------------
public class SellTicketDemo {
public static void main(String[] args) {
// SellTicket st=new SellTicket();
SellTicket02 st=new SellTicket02();
Thread t1=new Thread(st,"窗口一");
Thread t2=new Thread(st,"窗口二");
Thread t3=new Thread(st,"窗口三");
t1.start();
t2.start();
t3.start();
}
}
|
|