首页 > 代码库 > 多线程同步-买票系统

多线程同步-买票系统

 

 窗口售票 简单同步

 

 

package IO;

public class DemoTicket implements Runnable {
    
    private int tickets = 100;
    
    public static void main(String[] args) {
        DemoTicket mt = new DemoTicket();

      Thread t1=new Thread(mt);  //创建线程 t1和t2
      Thread t2=new Thread(mt);
      t1.setName("窗口1");       //线程命名
      t2.setName("窗口2");
      t1.start();
      t2.start();

    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true) {
            synchronized(this) {
                if(tickets <= 0) {
                    break;
                }
                try {
                    Thread.sleep(10);                //线程1睡,线程2睡
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "...这是第" + tickets-- + "号票");
            }
    
        }
    }
    
}

 

多线程同步-买票系统