package lsq;
public class main {
public static void main ( String[ ] args) throws InterruptedException {
storeshouse store = new storeshouse ( ) ;
Thread Producer1 = new Thread ( new Producer ( store) ) ;
Producer1. setName ( "生产者1" ) ;
Thread Producer2 = new Thread ( new Producer ( store) ) ;
Producer2. setName ( "生产者2" ) ;
Thread consumer1 = new Thread ( new consumer ( store) ) ;
consumer1. setName ( "消费者1" ) ;
Thread consumer2 = new Thread ( new consumer ( store) ) ;
consumer2. setName ( "消费者2" ) ;
Producer1. start ( ) ;
Producer2. start ( ) ;
Thread. sleep ( 100 ) ;
consumer1. start ( ) ;
consumer2. start ( ) ;
}
}
package lsq;
import java. awt. color. ProfileDataException;
import java. util. function. Consumer;
public class storeshouse {
private produces[ ] produce = new produces [ 10 ] ;
private int top = 0 ;
public synchronized void push ( produces pro) {
while ( top == produce. length) {
try {
System. out. println ( "仓库已满,produeces wait" ) ;
wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
produce[ top++ ] = pro;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "生产了产品" ) ;
System. out. println ( "prodecer notifyall" ) ;
notifyAll ( ) ;
}
public synchronized produces pop ( ) {
while ( top == 0 ) {
try {
System. out. println ( "仓库已空,consumer wait" ) ;
wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
top-- ;
produces pro = new produces ( produce[ top] . getid ( ) , produce[ top] . getname ( ) ) ;
produce[ top] = null;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "消费了产品" ) ;
System. out. println ( "Consumer notifyall" ) ;
notifyAll ( ) ;
return pro;
}
}
package lsq;
public class produces {
private int id;
private String name;
public produces ( int ID , String names) {
this . id= ID;
this . name= names;
}
public int getid ( ) {
return id;
}
public String getname ( ) {
return name;
}
public void setid ( int ID) {
this . id= ID;
}
public void setname ( String Name) {
this . name= Name;
}
public String getinformation ( ) {
return "产品ID为:" + id + "产品名称为:" + name;
}
}
package lsq;
public class Producer implements Runnable {
private storeshouse store;
public Producer ( storeshouse store2) {
this . store= store2;
}
public void run ( ) {
int i= 0 ;
while ( i< 10 ) {
i++ ;
produces pro = new produces ( i, "name" + i) ;
store. push ( pro) ;
try {
Thread. sleep ( 100 ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
}
package lsq;
public class consumer implements Runnable {
private storeshouse store;
public consumer ( storeshouse sto) {
this . store= sto;
}
public void run ( ) {
int i= 0 ;
while ( i< 10 ) {
i++ ;
store. pop ( ) ;
try {
Thread. sleep ( 100 ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
}