多线程

来源:互联网 发布:2015年贵州旅游数据 编辑:程序博客网 时间:2024/06/05 15:55

//使用同步方法

publicclass Test5{

    publicstaticvoid main(String[]args) {

       MyThread mt = new MyThread();

       new Thread(mt,"A").start();

       new Thread(mt,"B").start();

       new Thread(mt,"C").start();

    }

}

class MyThreadimplements Runnable{

    privateintticket = 10;

    @Override

    publicvoid run() {

       for(inti = 0 ; i < 20 ;i++){

           this.sale();

       }

    }

    publicsynchronizedvoid sale()同步方法

       if(this.ticket > 0){

           try {

              Thread.sleep(100);

           } catch (InterruptedExceptione) {

              e.printStackTrace();

           }

           System.out.println(Thread.currentThread().getName()+"saleticket=" +this.ticket--);

       }

    }  

}