您的位置:首页 > 其它

Thread(生产者和消费者)

2017-09-08 00:28 204 查看
package com.gdut.lang.thread;

public class ProducerAndConsumer {

public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);

new Thread(p).start();
new Thread(c).start();
}

}

class WoTou {
private int id;

public WoTou(int id) {
this.id = id;
}

public String toString() {
return "WoTou : " + id;
}
}

class SyncStack {
int index = 0;
WoTou[] arrWT = new WoTou[5];

public synchronized void push(WoTou wt) {
if ( index == arrWT.length ) { //窝头数组满了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
arrWT[index] = wt;
index++;
this.notify();
}

public synchronized WoTou pop() {

if ( index == 0 ) { //数组里面没窝头了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
this.notify();
return arrWT[index];

}
}

class Producer implements Runnable {
SyncStack ss = null;
public Producer(SyncStack ss) {
this.ss = ss;
}

public void run() {
for (int i = 0; i < 20; i++) {
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("Producer: " + wt);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

class Consumer implements Runnable {
SyncStack ss = null;
public Consumer(SyncStack ss) {
this.ss = ss;
}

@Override
public void run() {
for ( int i = 0; i < 20; i++ ) {
WoTou wt = ss.pop();
System.out.println("Consumer: " + wt);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}


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