首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

编写一个 火车站卖票程序-3个窗口同时售票

2013-01-25 
编写一个 火车站卖票程序--3个窗口同时售票 /*实现Runnable接口 创建Thread类共享一个数据 编写一个 火车

编写一个 火车站卖票程序--3个窗口同时售票

 

/*实现Runnable接口 创建Thread类  共享一个数据 
编写一个 火车站卖票程序--3个窗口同时卖票  */class PP implements Runnable{  //实现了一个Runnable接口的类PPpublic int tickets=100;     //共同拥有100张票String str=new String("123");  //创建String对象  把局部名字传进同步参数里 public void run(){  while(true){ //当条件为真 synchronized(this.str){   //(同步的参数必须是一个对象的名字) //当tt线程判断条件为真,把str锁上,执行内部的代码,当内部代码没有执行完,CPU有可能会被其他线程抢去,但是当判断同步有锁//它就会在外面等着,进不来,保证了只有一个线程在内部执行,直到tt把内部代码执行完退出之后,会在次跟tt1在同一起跑线上抢占CPU的执行权if(tickets>0){System.out.println(Thread.currentThread().getName()+"卖出去的票数是:"+tickets);tickets--;}else{break;}}}}}public class Threade_14 {public static void main(String[] args) {PP pp =new PP();Thread tt1=new Thread(pp); //构造Thread对象 实现Runnable类PPThread tt2=new Thread(pp);Thread tt3=new Thread(pp);tt1.start();  //开启线程tt2.start();tt3.start();}}


 

1楼zhangchao_nwsuaf昨天 10:15
总感觉你 synchronized()里面传的值不太对,结果发现这个应该传入this。表示当前的对象,这样就更加清楚了。
Re: zhangchao_nwsuaf昨天 10:40
回复zhangchao_nwsuafn之所以用this,是为了减少new String 的开销。。
Re: woshi2512901978昨天 12:32
值传的没错的,不过为了更加清楚,恩 我加了个this.str

热点排行