您的位置:首页 > 编程语言 > Java开发

关于网宿厦门研发中心笔试的一道PV操作题:利用java中的多线程实现生产者与消费者的同步问题

2012-10-12 22:17 961 查看
票据为同步资源:每一时刻资源池中仅存在一张可供使用的票据
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();
}
}








                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐