package com.adu;

import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

public class Station implements Runnable {

         //定义火车站总的票数
	private int ticketsCount = 1000;
          //定义要显示售票情况的窗口对象
	JFrame jf = new JFrame("售票实时显示窗口");
         //定义四个用于显示售票情况的显示文本域,用于显示售票情况
	JTextArea jt1 = new JTextArea("");
	JTextArea jt2 = new JTextArea("");
	JTextArea jt3 = new JTextArea("");
	JTextArea jt4 = new JTextArea("");

	//初始化票数及窗口
	public Station(){	

             //把文本域添加到滚动条上
	    JScrollPane scroll = new JScrollPane(jt1); 
	    JScrollPane scrol2 = new JScrollPane(jt2); 
	    JScrollPane scrol3 = new JScrollPane(jt3); 
	    JScrollPane scrol4 = new JScrollPane(jt4); 

	         jf.setSize(800, 500);//设置窗体大小
                     //设置窗体布局
		jf.setLayout(new GridLayout(2, 2, 10, 10));
		jf.setBackground(Color.red);
                  //添加滚动条
		jf.add(scroll);
		jf.add(scrol2);
		jf.add(scrol3);
		jf.add(scrol4);

		jf.setVisible(true);//设为可见
	//关闭窗体
	jf.setDefaultCloseOperation                                                     (WindowConstants.EXIT_ON_CLOSE);

	}



	public void run() {
                   //获取当前线程的名字,即窗口号
		String name = Thread.currentThread().getName();

		try {

			Thread.sleep((long) (Math.random() * 10));

		} catch (InterruptedException e) {

			System.out.println(e.getMessage());
		}

	  //显示售票情况的方法
		while (ticketsCount > 0) {

			synchronized (this) {

				if (ticketsCount > 0) {

					if (name.equals("1")) {
						jt1.append("1号窗口售出第:" + ticketsCount + "张票\n");

					}
					if (name.equals("2")) {
						jt2.append("2号窗口售出第:" + ticketsCount + "张票\n");

					}
					if (name.equals("3")) {
						jt3.append("3号窗口售出第:" + ticketsCount + "张票\n");

					}
					if (name.equals("4")) {
						jt4.append("4号窗口售出第:" + ticketsCount + "张票\n");

					}

					ticketsCount--;

				}

			}

		}
	}

	public static void main(String[] args) {

                  //实例化火车站对象Station
		Station sta = new Station();

                  //创建匿名线程并启动
		new Thread(sta, "1").start();
		new Thread(sta, "2").start();
		new Thread(sta, "3").start();
		new Thread(sta, "4").start();

	}
}