package com.threadSecurity;
/**
* 线程安全
* @author tfq
* @datetime 2011-09-06
*/
public class Demol_1 {
public static void main(String[] args) {
//定义三个窗口售票
TicketWindow tw1=new TicketWindow();
Thread t1=new Thread(tw1);
Thread t2=new Thread(tw1);
Thread t3=new Thread(tw1);
t1.start();
t2.start();
t3.start();
}
}
// 售票窗口
class TicketWindow implements Runnable{
//一共2000张票
private int nums=20;
public void run(){
while(true){
synchronized(this){
//1秒出一张票
try {
Thread.sleep(1000);
//先判断是否还有票
if(nums >0){
//显示售票信息
System.out.println("窗口"+Thread.currentThread().getName()+"在售出第"+nums+"张票");
nums--;
}else{
System.out.println("票已经卖完了!");
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}