JAvaマルチスレッド-生産者消費者問題
2509 ワード
package com.fsun.research.thread.producercustomer;
import java.util.Stack;
public class MainTest {
public static void main(String[] args) {
// :
Stack<Ticket> stack=new Stack<Ticket>();
Thread thread1=new Thread(new TicketProducer(stack, " "));
Thread thread2=new Thread(new TicketCustomer(stack, " "));
thread1.start();
thread2.start();
}
}
Ticket:
package com.fsun.research.thread.producercustomer;
import java.util.Date;
public class Ticket {
private int cost; //
private Date date; //
public Ticket(int cost, Date date) {
super();
this.cost = cost;
this.date = date;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
TicketCustomer:
package com.fsun.research.thread.producercustomer;
import java.util.Stack;
//
public class TicketCustomer implements Runnable{
private Stack<Ticket> ticketPool;
private String displayName;
public TicketCustomer(Stack<Ticket> ticketPool,String displayName){
this.ticketPool=ticketPool;
this.displayName=displayName;
}
@Override
public void run() {
Ticket ticket=null;
while(true){
synchronized (ticketPool) {
if(ticketPool.isEmpty()){
ticketPool.notify();
//
try {
ticketPool.wait(); //
} catch (InterruptedException e) {
}
}else{
ticket=ticketPool.pop();
System.out.println(displayName+" ");
}
}
}
}
}
TicketProducer:
package com.fsun.research.thread.producercustomer;
import java.util.Date;
import java.util.Stack;
//
public class TicketProducer implements Runnable{
private String displayName;
private Stack<Ticket> ticketPool;
public TicketProducer(Stack<Ticket> ticketPool,String displayName){
this.ticketPool=ticketPool;
this.displayName=displayName;
}
@Override
public void run() {
while(true){
synchronized (ticketPool) {
if(ticketPool.isEmpty()){
Ticket ticket=new Ticket(20, new Date());
ticketPool.push(ticket);
System.out.println(displayName+" ");
ticketPool.notify();
}else{
try {
ticketPool.wait();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName()+" ");
}
}
}
}
}
}