Java多线程售票一张票多买问题

blic class Test {
    public static void main(String[] args) {
        ThreadTicket ticket = new ThreadTicket();
        Thread t1 = new Thread(ticket,"线程A");
        Thread t2 = new Thread(ticket,"线程B");
        t1.start();
        t2.start();

    }
}

class ThreadTicket implements Runnable {
    int ticket = 10;

    @Override
    public  void run() {
          {
            while( ticket > 0) {
                sale();
            }
        }
    }
    
    private synchronized void sale() {//不加synchronized会出现一张票多买问题
        
        if (ticket > 0) {
            try {
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " buy---" + ticket--);
        } 
    }

}

结果:

Java多线程售票一张票多买问题_第1张图片

参考

https://blog.csdn.net/zouxucong/article/details/54409801

https://blog.csdn.net/vinegar93/article/details/51452112

 

转载于:https://www.cnblogs.com/venje/p/9284550.html

你可能感兴趣的:(Java多线程售票一张票多买问题)