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--); } } }
结果:
参考
https://blog.csdn.net/zouxucong/article/details/54409801
https://blog.csdn.net/vinegar93/article/details/51452112