黑马程序员技术交流社区

标题: 请教一个多线程起名字问题 [打印本页]

作者: 穆顺涛    时间: 2015-5-2 15:23
标题: 请教一个多线程起名字问题
怎么给下面的多线程售票窗口改名为“售票窗口1”、“售票窗口2”、“售票窗口3”
class Test6
{
        public static void main(String[] args)
        {  
                Ticket ti=new Ticket();
                SealWindow sw=new SealWindow(ti);
                TicketSealCenter tsc=new TicketSealCenter(ti);
                //开辟三个售票窗口,一个售票中心
                Thread t1=new Thread(sw);
                Thread t2=new Thread(sw);
                Thread t3=new Thread(sw);
                Thread t4=new Thread(tsc);
               
                t1.start();
                t2.start();
                t3.start();
                t4.start();
               
               


        }
}
class Ticket//资源
{
        private int count=0;//记录生产的票数
        private String name;
        private boolean flag;
        public synchronized void setTicket()
        {
                while(flag)
                        try
                        {
                                wait();
                        }
                        catch (Exception e)
                        {
                        }
                        count++;
                        System.out.println(Thread.currentThread().getName()+"--生产票--"+count);
                        flag=true;
                        notifyAll();
        }
        public synchronized void sealTicket()
        {
                while(!flag)
                        try
                        {
                                wait();
                        }
                        catch (Exception e)
                        {
                        }
                        Thread.currentThread().setName("售票中心");
                        System.out.println(Thread.currentThread().getName()+".....消费票....."+count);
                        //当消费出500张票时return,避免唤醒t1,t2,t3中等待的线程而继续执行setTicket()方法多生产一张票。
                        if(count==500)
                                return;
                        flag=false;
                        notifyAll();
        }
}
class SealWindow implements Runnable//消费票
{
        private Ticket ti;
       
        SealWindow(Ticket ti)
        {
                this.ti=ti;
        }
        public void run()
        {       
                for(int x=0;x<500;x++)
                        ti.setTicket();
        }
       
}
class TicketSealCenter implements Runnable//生产票
{
        private Ticket ti;
        TicketSealCenter(Ticket ti)
        {
                this.ti=ti;
        }
        public void run()
        {       
                for(int x=0;x<500;x++)
                        ti.sealTicket();
        }
}
作者: cyr    时间: 2015-5-2 15:40
Thread有包含线程名字的构造方法的呀,在new的时候初始化就可以了Thread(Runnable target, String name);
作者: ninjaes    时间: 2015-5-2 15:45
感觉super(name)即可的样子




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2