关于网宿厦门研发中心笔试的一道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 block
			e.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 block
			e.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();
}
}







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值