码迷,mamicode.com
首页 > 编程语言 > 详细

多线程售票系统的感想

时间:2016-07-23 09:04:29      阅读:410      评论:0      收藏:0      [点我收藏+]

标签:

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中自动起名的那个
 }
}

多线程售票系统的感想

标签:

原文地址:http://www.cnblogs.com/daoxiang1992/p/5697808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!