import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Mythread4 implements Runnable{
private int ticket=100;
public void run() {
for(int i=0;i<200;i++){
synchronized (this) {
if(ticket>0){
try {
Thread.sleep(500);
System.out.println("出票窗口:"+Thread.currentThread().getName());
System.out.println("剩余票数:"+ticket--);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Mythread5 implements Runnable{
private int ticket=100;
public void run() {
Lock lock=new ReentrantLock();
for(int i=0;i<200;i++){
lock.lock();
if(ticket>0){
try {
try {
Thread.sleep(500);
System.out.println("出票窗口:"+Thread.currentThread().getName());
System.out.println("剩余票数:"+ticket--);
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally{
lock.unlock();
}
}
}
}
}
public class Mythread3 {
public static void main(String[] args) {
Mythread4 p=new Mythread4();
Thread t1=new Thread(p,"1");
Thread t2=new Thread(p,"2");
Thread t3=new Thread(p,"3");
t1.start();
t2.start();
t3.start();
}
}