多线程同步卖票demo

来源:互联网 发布:网络教育退学 编辑:程序博客网 时间:2024/05/21 01:31
public class Test1 {public static void main(String[] args) {    TestThread te = new TestThread();    Thread te1 = new Thread(te);    Thread te2 = new Thread(te);    Thread te3 = new Thread(te);    Thread te4 = new Thread(te);    Thread te5 = new Thread(te);        te1.setName("1");        te2.setName("2");        te3.setName("3");        te4.setName("4");        te5.setName("5");        te1.start();        te2.start();        te3.start();        te4.start();        te5.start();    }}   class TestThread implements Runnable {    int size=1000;    public synchronized void sale(){         if(size>0){             size--;             System.out.println(Thread.currentThread().getName()+"正在卖票,还剩"+size+"张");          }else if(size==0){             System.out.println("票已售完!");         }        }    public void run(){        while(size>0){        sale();        }    }}
原创粉丝点击