寫出一組模擬生產者/消費者的協作程序
其中包括一個WoTou
一個MsgQueue
一個Produer
一個Consumer
一個TestMain
要求
對於MsgQueue
get()方法需要阻塞
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p
Consumer c
Producer p
Consumer c
}
}
class WoTou<T> {
int id;
WoTou(int id) {
this
}
public String toString() {
return
}
}
class SyncStack {
int index =
WoTou[] arrWT = new WoTou[
public void push(WoTou wt) {
while(index == arrWT
try {
this
} catch (InterruptedException e) {
e
}
}
this
arrWT[index] = wt;
index ++;
}
public WoTou pop() {
while(index ==
try {
this
} catch (InterruptedException e) {
e
}
}
this
index
return arrWT[index];
}
}
class Producer implements Runnable {
SyncStack ss = null;
String a;
Producer(SyncStack ss
this
this
Thread t=new Thread(this
t
}
public void run() {
for(int i=
synchronized(ss){
WoTou wt = new WoTou(i);
ss
System
try {
Thread
} catch (InterruptedException e) {
e
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
String a;
Thread t;
Consumer(SyncStack ss
this
this
t=new Thread(this
t
}
public void run() {
for(int i=
synchronized(ss){
WoTou wt = ss
System
try {
Thread
} catch (InterruptedException e) {
e
}
}
}
}
p
p
p
c
c
p
c
c
p
p
c
p
p
c
p
p
c
p
p
c
c
p
c
p
p
p
棧裡有
作為多線程交互一的一個重要應用
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p)
new Thread(p)
new Thread(p)
new Thread(c)
}
}
class WoTou {
int id;
WoTou(int id) {
this
}
public String toString() {
return
}
}
class SyncStack {
int index =
WoTou[] arrWT = new WoTou[
public synchronized void push(WoTou wt) {
while(index == arrWT
try {
this
} catch (InterruptedException e) {
e
}
}
this
arrWT[index] = wt;
index ++;
}
public synchronized WoTou pop() {
while(index ==
try {
this
} catch (InterruptedException e) {
e
}
}
this
index
return arrWT[index];
}
}
class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this
}
public void run() {
for(int i=
WoTou wt = new WoTou(i);
ss
System
try {
Thread
} catch (InterruptedException e) {
e
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this
}
public void run() {
for(int i=
WoTou wt = ss
System
try {
Thread
} catch (InterruptedException e) {
e
}
}
}
}
運行後的結果棧裡有
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27299.html