其他分享
首页 > 其他分享> > 生产者与消费者试验

生产者与消费者试验

作者:互联网

package t1;

public class TestThread5 {

public static void main(String[] args) {
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}
}

class Shared {
private char c;
private volatile boolean writeable = true;

synchronized void setSharedChar(char c) {
while (!writeable) {
try {
wait();
} catch (Exception e) {
}
}

this.c = c;
writeable = false;
notify();
}

synchronized char getSharedChar() {
while (writeable) {
try {
wait();
} catch (Exception e) {
}
}

writeable = true;
notify();
return c;
}
}

class Producer extends Thread {
private final Shared s;

Producer(Shared s) {
this.s = s;
}

@Override
public void run() {

for (char ch = 'a'; ch <= 'z'; ch++) {
synchronized (s) {
s.setSharedChar(ch);
System.out.println(ch + " produced by producer");
}
}
}
}

class Consumer extends Thread {
private final Shared s;

public Consumer(Shared s) {
this.s = s;
}

@Override
public void run() {
char ch;
do {
synchronized (s) {
ch = s.getSharedChar();
System.out.println(ch + " consumed by consumer");
}
} while (ch != 'z');
}
}

多次执行打印结果:

a produced by producer
a consumed by consumer
b produced by producer
b consumed by consumer
c produced by producer
c consumed by consumer
d produced by producer
d consumed by consumer
e produced by producer
e consumed by consumer
f produced by producer
f consumed by consumer
g produced by producer
g consumed by consumer
h produced by producer
h consumed by consumer
i produced by producer
i consumed by consumer
j produced by producer
j consumed by consumer
k produced by producer
k consumed by consumer
l produced by producer
l consumed by consumer
m produced by producer
m consumed by consumer
n produced by producer
n consumed by consumer
o produced by producer
o consumed by consumer
p produced by producer
p consumed by consumer
q produced by producer
q consumed by consumer
r produced by producer
r consumed by consumer
s produced by producer
s consumed by consumer
t produced by producer
t consumed by consumer
u produced by producer
u consumed by consumer
v produced by producer
v consumed by consumer
w produced by producer
w consumed by consumer
x produced by producer
x consumed by consumer
y produced by producer
y consumed by consumer
z produced by producer
z consumed by consumer

 

标签:writeable,ch,消费者,生产者,consumed,produced,试验,Shared,public
来源: https://www.cnblogs.com/dengw125792/p/12599515.html