编写程序 火车站2个窗口同时卖100张票 同步中嵌套同步。
/* 如果同步函数被静态修饰后,使用的锁是什么呢?通过验证,发现不在是this。因为静态方法中也不可以定义this。静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象。类名.class 该对象的类型是Class静态的同步方法,使用的锁是该方法所在类的字节码文件对象。 类名.class */class Thre implements Runnable{private static int tickets = 100; //100张票boolean flas =true; //判断flas是否为真/** 同步线程 如果flas为真 把当前本类对象上锁,如果票数大于0,sleep10秒,这时CPU会被其他线程抢去,判断flas为假, 执行show方法,一看show方法上有锁,就进不去,在外面等着,这时,sleep有可能醒了,就打印输出当前对象的引用名字和 票数减1; 执行完退出之后,此线程回到起跑线,和其他线程共同争抢CPU的执行权限. */public void run() {if(flas){while(true){synchronized(Thre.class) {if(tickets>0){try{Thread.sleep(10);System.out.println(Thread.currentThread().getName()+"run........"+ tickets--);} catch(Exception e){}}}}}elsewhile(true)show(); }/* *静态 同步代码快 分配内存的时候,分配在静态代码区内,static没有对象,类名也可以执行,所以静态代码快要同步 *必须要填类名的.class文件 */public static synchronized void show(){if(tickets>0){try{Thread.sleep(10);System.out.println(Thread.currentThread().getName()+"show..."+ tickets--);} catch(Exception e){}}}}/* * 主函数 开启2个线程 */class Threade_16{public static void main(String[] args){Thre tt = new Thre();Thread t1 = new Thread(tt);Thread t2 = new Thread(tt);t1.start();try{Thread.sleep(10);}catch(Exception e ){}tt.flas = false; t2.start();}}