public class Test { 
/* 
 * * 一辆公交车70个座位,只能从前后门下车,多线程模拟这个过程, 
         * 并且输出剩下剩余的座位数。 
 */ 
        public static void main(String[] args) { 
                new Bus("前门").start(); 
                new Bus("后门").start(); 
        } 
} 
 
class Bus extends Thread { 
        //定义静态共享变量 
        private static int seats = 1; 
        //继承Thread有参构造,给线程命名 
        public Bus(String name) { 
                super(name); 
        } 
 
        public void run() { 
                while (true) { 
                        //锁对象Bus.class 
                        synchronized (Bus.class) { 
                                //判断人全下后结束线程 
                                if (seats > 70) { 
                                        break; 
                                } 
                                //睡眠只是为了测试程序,可以注释掉 
                                try { 
                                        Thread.sleep(100); 
                                } catch (InterruptedException e) { 
                                        e.printStackTrace(); 
                                } 
                                 
                                //假设车上70个座位都坐满了 
                                System.out.println(getName() + "下车, 剩余" + seats + "座位"); 
                                seats++; 
                        } 
                } 
        } 
} |