多线程售票系统的感想

package 异常练习;
class Seel implements Runnable{
 private String name;
 private int ticket=100;
 Seel(String name){
  this.name=name;
 }

 public void run(){
  while(true){
   if(ticket>0){
    System.out.println(Thread.currentThread().getName()+"正在售票"+"........"+"余额为"+(--ticket));
   }
  }
 }
}
public class text26 {
 public static void main(String[] args){
  
  Seel S=new Seel("售票机1");
  
  /*Seel S2=new Seel("售票机2");
  Seel S3=new Seel("售票机3");
  Seel S4=new Seel("售票机4");
  Seel S5=new Seel("售票机5");
  */
  Thread t1=new Thread(S);
  Thread t2=new Thread(S);
  Thread t3=new Thread(S);
  Thread t4=new Thread(S);
  Thread t5=new Thread(S);
  t1.start();
  t2.start();
  t3.start();
  t4.start();
  //在售票系统中我们不能new出多个子类多相,因为它们是相对独立的,多线程的开启是相互不干涉的,
  //而售票的总数在多台售票机中是共享的,所有我们要使用同一个子类,然后把这个子类作为
  //参数传递给Tread类,然后让Tread new出多个对象来实现多台售票机的现象。
  //这样虽然我们开启了Thread的多线程模式,但是因为它传递进来的参数Seel类是唯一的,导致这个类中的方法、属性是共享共影响的
 }
}

........................

 

 

class Seel implements Runnable{
 private String name;
 private int ticket=100;
 Seel(String name){
  this.name=name;
 }

 public void run(){
  while(true){
   if(ticket>0){
    System.out.println(Thread.currentThread().getName()+"正在售票"+"........"+"余额为"+(--ticket));
   }
  }
 }
}
public class text29 {
 public static void main(String[] args){
  
  Seel S=new Seel("售票"); 
  Thread t1=new Thread(S,"售票机1");
  Thread t2=new Thread(S,"售票机2");
  Thread t3=new Thread(S,"售票机3");
  Thread t4=new Thread(S,"售票机4");
  Thread t5=new Thread(S,"售票机5");
  t1.start();
  t2.start();
  t3.start();
  t4.start();
  
  //在这次改进中我发现Thread构造器中有个类型是Thread(Runnable target, String name){};,里面的String name被传递了信息,
  //那么这个信息会覆盖Thread中自动起名的那个
 }
}

posted @ 2016-07-23 08:42  对与错  阅读(447)  评论(1编辑  收藏  举报