java线程编程实现在线卖票
public class ThreadTest {
public static void main(String[] args) {
booking bk1=new booking("一号");
booking bk2=new booking("二号");
booking bk3=new booking("三号");
booking bk4=new booking("四号");
bk1.start();
bk2.start();
bk3.start();
bk4.start();
}
}
class booking extends Thread{
static int total=100;
public booking(String name){
super(name);
}
Object obj="aa";
@Override
public void run() {
// TODO Auto-generated method stub
while(total>0){
synchronized(obj){
if(total>0){
System.out.println(super.getName()+"卖了第"+total+"张票");
total--;
}else{
System.out.println("票已售完");
}
try {
this.sleep(10);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
super.run();
}