多线程3-池

来源:互联网 发布:通话数据统计软件 编辑:程序博客网 时间:2024/06/05 08:11

Thread t=...

t.join()

------------------------------------------------ 

lock可以做成static 的对象

也可以在main里面作为创建局部对象 然后传给线程里面 因为对象存在heap里面  对于传给线程 都是同一个线程

----------------------------------------------

synchronized里面是串行的 同步代码块

能避免尽量避免

同步代码块执行期间,线程始终持有对象的监控权,其他线程处于阻塞状态

----------------------------------------------

class  Saler extends Thread{

  private String name;

  private TicketPool pool;

  public Saler(String name, TicketPool pool ){

    this.name = name;

    this.pool =pool;


  }

  public void run(){

    while(true){

      int no=pool.getTicket();

      if(no == 0 ){

        return;

      }

      else{

        print(name+no);

      }

    }

  }

}


class TicketPool{

  private int tickets =100;

  public int getTicket(){

  //同步代码块 它以票池为锁旗标

    synchronized(this){

      int temp = tickets;

      tickets = tickets -1;

      return temp>0? temp: 0;

   }

  }

}

--------------------------

class TicketPool{

  private int tickets =100;

  publicsynchronized int getTicket(){

  //同步代码块 它以票池为锁旗标

    //synchronized(this){

      int temp = tickets;

      tickets = tickets -1;

      return temp>0? temp: 0;

   //}

  }

}


把对象自己当成票池 跟上面一样

---------------------------

class ThreadDemo{

 public static void main(String[] args){

    TicketPool pool = new TicketPool();

    Saler s1 = new Saler("s1", pool);

    Saler s2 = new Saler("s2", pool);

    s1.start();

    s2.start();

  }

}