package com.first;
import java.util.LinkedList;
public class productandconsumer {
public static void main(string[] args) {
final market market = new market();
new thread(new product(market)).start();
new thread(new product(market)).start();
new thread(new consume(market)).start();
new thread(new consume(market)).start();
new thread(new consume(market)).start();
}
}
class producted{
int number;
public int getnumber() {
return number;
}
public void setnumber(int number) {
number = number;
}
public producted(int number) {
this.number = number;
}
}
class market{
private linkedlist <producted> list = new linkedlist<producted>();
int maxsize = 10;
public synchronized void put(producted p){
while(checksize() >= maxsize){
try {
system.out.println("ย๚มห");
wait();
} catch (interruptedexception e) {
e.printstacktrace();
}
}
list.addfirst(p);
notifyall();
}
public synchronized producted take(){
while(checksize()<= 0)
try {
system.out.println("รปมห");
wait();
} catch (interruptedexception e) {
e.printstacktrace();
}
producted pt = list.removelast();
notifyall();
return pt;
}
public int checksize(){
return list.size();
}
}
class product implements runnable{
market market = null;
public product(market market){
this.market = market;
}
@override
public void run() {
int i = 0;
while(true){
try {
thread.sleep(100);
} catch (interruptedexception e) {
e.printstacktrace();
}
producted p = new producted(i++);
market.put(p);
}
}}
class consume implements runnable{
market market = null;
public consume(market market){
this.market = market;
}
@override
public void run() {
while(true){
try {
thread.sleep(150);
} catch (interruptedexception e) {
e.printstacktrace();
}
market.take();
}
}} |
|