解决方法一:
注意:在synchronized中的同步监视器(锁)只能是唯一的。
方式二,同步方法
方法三: lock()
lock锁
public class ThreadTest6 {public static void main(String[] args) {Window w = new Window();Thread t1 = new Thread(w);Thread t2 = new Thread(w);Thread t3 = new Thread(w);t1.setName("线程一");t2.setName("线程二"); t3.setName("线程三");t1.start();t2.start();t3.start();}}class Window implements Runnable{private int ticket = 100;
// 1定义lockprivate ReentrantLock lock = new ReentrantLock();@Overridepublic void run() {while(true) {try {//2.调用Locklock.lock();if(ticket > 0) {try {Thread.currentThread().sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName() + ":售票,票号为:" + ticket);ticket --;}else break;}finally {//3.调用解锁的方法:unlock()lock.unlock();}}}}