多线程问题,,,,,

用多线程,实现如下功能,
用户去火车站取票,,有四个窗口,,票自己订,,,,实现一下,新手,,,求救,

package xatu.zsl.main;

/**

  • Created by zsl on 2017/8/9. */ public class Demo { public static void main(String[] args) { //使用同一个runnable保证 tickateNum只初始化一次 MyThread myThread = new MyThread(); Thread thread1 = new Thread(myThread, "窗口1"); Thread thread2 = new Thread(myThread, "窗口2"); Thread thread3 = new Thread(myThread, "窗口3"); Thread thread4 = new Thread(myThread, "窗口4"); System.out.println("开始买票!!"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.out.println("买票结束!!"); } }

class MyThread implements Runnable {

//初始化有十张票,,设置为可见的整形,防止并发操作出错
volatile int ticketNum = 100;
Object object = new Object();

public void run() {
    while (this.ticketNum > 0) {
        synchronized (object) {//保证扣票和输出是一个整体
            if (this.ticketNum > 0) {   //防止卖出负票
                //售出一张
                this.ticketNum = this.ticketNum - 1;
                System.out.println(Thread.currentThread().getName() + "售出一张火车票,还剩" + this.ticketNum + "张");
            } else {
                return;
            }
        }
    }
}

}

package xatu.zsl.main;

/**

  • Created by zsl on 2017/8/9. */ public class Demo { public static void main(String[] args) { //使用同一个runnable保证 tickateNum只初始化一次 MyThread myThread = new MyThread(); Thread thread1 = new Thread(myThread, "窗口1"); Thread thread2 = new Thread(myThread, "窗口2"); Thread thread3 = new Thread(myThread, "窗口3"); Thread thread4 = new Thread(myThread, "窗口4"); System.out.println("开始买票!!"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.out.println("买票结束!!"); } }

class MyThread implements Runnable {

//初始化有十张票,,设置为可见的整形,防止并发操作出错
volatile int ticketNum = 100;
Object object = new Object();

public void run() {
    while (this.ticketNum > 0) {
        synchronized (object) {//保证扣票和输出是一个整体
            if (this.ticketNum > 0) {   //防止卖出负票
                //售出一张
                this.ticketNum = this.ticketNum - 1;
                System.out.println(Thread.currentThread().getName() + "售出一张火车票,还剩" + this.ticketNum + "张");
            } else {
                return;
            }
        }
    }
}

}


哎,,,,这格式也是让人无语了,,,,仅供参考吧,,,,不懂随时追问