关于网宿厦门研发中心笔试的一道PV操作题:利用java中的多线程实现生产者与消费者的同步问题
票据为同步资源:每一时刻资源池中仅存在一张可供使用的票据
public class Ticket {private int ticket=-1;synchronized public void setTicket(int ticket)//生产票据{if(this.ticket!=-1)try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.ticket=ticket;System.out.println("生产产品"+this.getClass().getName()+this.ticket);notify();}synchronized public void getTicket()//消费票据 {if(this.ticket==-1)try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("消费产品"+this.getClass().getName()+this.ticket); this.ticket=-1; notify();}}
生产者类通过调用同步资源的生产函数来实现产生票据
public class Product implements Runnable { public Ticket ticket; public Product(Ticket ticket) { this.ticket=ticket; }public void run() {// TODO Auto-generated method stub for(int i=0;i<10;i++) {ticket.setTicket(i); }}}消费者同样通过调用同步资源中的set函数来重新设置资源池public class Consumer implements Runnable { public Ticket ticket; public Consumer(Ticket ticket) { this.ticket=ticket; }public void run() {// TODO Auto-generated method stub for(int i=0;i<10;i++) {ticket.getTicket(); }}}测试类public class ThreadTest {public static void main(String[] args){Ticket ticket=new Ticket();Product pro=new Product(ticket);Consumer con=new Consumer(ticket);Thread thread1=new Thread(pro);Thread thread2=new Thread(con);thread1.start();thread2.start();}}