不使用同步锁时造成的线程不安全问题(该例子尚未成功仍存在问题)
当回过头自己写该模式的时候发现出现了问题
自己动手写生产与消费模式
请看没使用线程通信前及没有加同步锁时的问题
.
// 生产者(producer)代码如下
public class Producer implements Runnable {
private ShareResource resource = null;
public Producer() {
}
public Producer(ShareResource shareResource) {
resource = shareResource;
}
@Override
public void run() {
resource.procuer();
}
}
/**
**消费者代码如下
*/
public class Consumer implements Runnable {
private ShareResource resource = null;
public Consumer() {
}
public Consumer(ShareResource resource) {
this.resource = resource;
}
@Override
public void run() {
resource.consumer();
}
}
//其次是共享资源的一个类
public class ShareResource {
private Food[] food = new Food[10];
public void procuer() {
for (int i = 0; i < food.length - 1; i++) {
if (i % 2 != 1) {
food[i] = new Food("包子","肉馅");
} else {
Food f = new Food("花卷","白糖");
food[i] = f;
}
System.out.println("生产:" + food[i]);
}
}
public void consumer() {
for (int i = food.length - 1; i > 0; i--) {
System.out.println("消费:" + food[i]);
food[i] = null;
}
}
/**
* 内部类对象
*/
class Food {
public String name;
public String type;
public Food() {
}
public Food(String name, String type) {
this.name = name;
this.type = type;
}
public String getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Food food = (Food) o;
return Objects.equals(name, food.name) &&
Objects.equals(type, food.type);
}
@Override
public int hashCode() {
return Objects.hash(name, type);
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
'}';
}
}
}
//最后我们的测试类
public class ProducerAndConumerTest {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
Producer prodecer = new Producer(shareResource);
Consumer consumer = new Consumer(shareResource);
Thread producerThread = new Thread(prodecer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
运行结果
当food数组为10时
第二次运行
消费者完全没机会
于是加入同步代码块
public void procuer() {
for (int i = 0; i < food.length - 1; i++) {
synchronized (this) {
if (i % 2 != 1) {
food[i] = new Food("包子", "肉馅");
System.out.println("生产:" + food[i]);
} else {
Food f = new Food("花卷", "白糖");
food[i] = f;
System.out.println("生产:" + food[i]);
}
}
}
}
public void consumer() {
for (int i = 0; i <= food.length - 1; i++) {
synchronized (this) {
if (food[i] != null) {
System.out.println("消费:" + food[i]);
food[i] = null;
}
}
}
}
运行结果
线程变成串行执行了
综上所诉完全没有到达我们生产者和消费者的运行结果。本人也深陷其中不得其解,若遇见一贵人还望不吝赐教。