1.阻塞队列
class producer implements Runnable{
private final BlockingQueue sharedQueue;
public producer(BlockingQueue sharedQueue){
this.sharedQueue=sharedQueue;
}
public void run(){
while(true){
for(int i=0;i<10;i++){
try{
System.out.println("producer products:"+i);
sharedQueue.put(i);
}catch(Exception e){
System.out.println(e);
}
}
}
}
}
class consumer implements Runnable{
private final BlockingQueue sharedQueue;
public consumer(BlockingQueue sharedQueue){
this.sharedQueue=sharedQueue;
}
public void run(){
while(true){
try{
int i=(Integer) sharedQueue.take();
System.out.println("consumd: "+i);
}catch(Exception e){
System.out.println(e);
}
}
}
}
public class Main {
public static void main (String[] args) {
BlockingQueue sharedQueue=new LinkedBlockingQueue(10);
Thread proThread=new Thread(new producer(sharedQueue));
Thread consThread=new Thread(new consumer(sharedQueue));
proThread.start();
consThread.start();
}
}
2.wait/notify()方法
class produce implements Runnable{
public Queue sharedQueue;
public produce(Queue sharedQueue){
this.sharedQueue=sharedQueue;
}
public void run(){
while(true){
synchronized(sharedQueue){
while(sharedQueue.size()==10){
try{
sharedQueue.wait();
}catch(Exception e){
System.out.println(e);
sharedQueue.notifyAll();
}
}
sharedQueue.offer(1);
System.out.println("producting");
sharedQueue.notifyAll();
}
}
}
}
class consumer implements Runnable{
public Queue sharedQueue;
public consumer(Queue sharedQueue){
this.sharedQueue=sharedQueue;
}
public void run(){
while(true){
synchronized(sharedQueue){
while(sharedQueue.size()==0){
try{
sharedQueue.wait();
}catch(Exception e){
System.out.println(e);
sharedQueue.notifyAll();
}
}
sharedQueue.poll();
System.out.println("consuming");
sharedQueue.notifyAll();
}
}
}
}
public class Main {
public static PriorityQueue<Integer> pq;
public static void main (String[] args) {
pq=new PriorityQueue<Integer>(10);
Thread pT=new Thread(new produce(pq));
Thread cT=new Thread(new consumer(pq));
pT.start();
cT.start();
}
}