线程经典 生产者消费者 两个完全不…

阅读 92

2022-05-31

package sell_ticket;


public class ThreadTicket {


      public static void main(String[] args) {

           

         

          

            MyThread m = new MyThread();        

            Thread t1 = new Thread(m);

            Thread t2 = new Thread(m);

            Thread t3 = new Thread(m);

            t1.start();

            t2.start();

            t3.start();

        }    

      

      

}


class MyThread implements Runnable{

    private int ticket=100;

    

    

    public void run(){

        while(true){

            

              try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

            // TODO Auto-generated catch block

                e.printStackTrace();

              }

            //用synchronized包起来,形成同步代码块,但后来发现用不用其实一样

            synchronized(this){

                if(ticket>0){

            

精彩评论(0)

0 0 举报