编写一个 火车站卖票程序--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();}}