捡捡基础去面试---多线程买票例子

2014-11-24 08:29:23 · 作者: · 浏览: 1
package t;  
  
public class Mt implements Runnable {  
  
    int ticket = 999;  
  
    @Override  
    public void run() {  
        // TODO Auto-generated method stub  
        int i = 0;  
        while (ticket > -1) { // 因为票数为0的时候也要放进去判断  
            synchronized (this) {  
                if (ticket == 0) {  
                    System.out.println(Thread.currentThread().getId()  
                            + "号窗口: 没票了");  
                    System.out.println(Thread.currentThread().getId()  
                            + "号窗口卖了 " + i + " 张票 , 收益: " + i * 0.5);  
                    break;  
                } else {  
                    System.out.println(Thread.currentThread().getId() + "号窗口: "  
                            + ticket--);  
                    i++;  
                }  
            }  
  
        }  
    }  
}  
 


package t;  
  
public class Test2 {  
  
    public static void main(String[] args) {  
          
        Mt mt = new Mt();  
        new Thread(mt).start();  
        new Thread(mt).start();  
  
    }  
  
}