private static List<String> object = new ArrayList<String>();
public static void main(String[] args) throws HttpException, IOException {
//模拟电影票
for(int i=0;i<10;i++){
object.add("电影票"+i);
}
object.add("电影票"+i);
}
//模拟购票
MyThread thread1 = test.new MyThread();
for(int i=0;i<20;i++){
thread1 = test.new MyThread();
thread1.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
synchronized (object) {
int listsize=(object.size()-1);
if(0<object.size()){
MyThread thread1 = test.new MyThread();
for(int i=0;i<20;i++){
thread1 = test.new MyThread();
thread1.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
synchronized (object) {
int listsize=(object.size()-1);
if(0<object.size()){
//模拟订票
System.out.println(Thread.currentThread().getName()+"来订票:"+object.get(listsize));
try {
System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态");
Thread.currentThread().sleep(2000);
System.out.println(Thread.currentThread().getName()+"来订票:"+object.get(listsize));
try {
System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态");
Thread.currentThread().sleep(2000);
//买票成功,将该票移出购票列表
object.remove(listsize);
object.wait();
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束");
}else{
System.out.println("来迟了");
}
}
}
}
object.remove(listsize);
object.wait();
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束");
}else{
System.out.println("来迟了");
}
}
}
}