且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【第06个代码模型】综合案例:生产者与消费者(解决同步问题)|学习笔记

更新时间:2022-02-20 02:40:42

开发者学堂课程【【名师课堂】Java 高级开发【第 06 个代码模型】综合案例:生产者与消费者(解决同步问题)】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:https://developer.aliyun.com/learning/course/372/detail/4566


【第 06 个代码模型】综合案例:生产者与消费者(解决同步问题)


范例

如果要想解决同步的问题,那么首先就应该立刻可以想到使用 synchronized 关键字来定义同步的操作方法,所以此时应该将代码修改如下

private string title;private string note;

public void setNote(string note) {

this.note = note;

}

将上方代码修改如下:

private string title;private String note;

public synchronized void get() {

try i

Thread.sleep( 50) ;

catch (InterruptedException e) {

e.printstackTrace();

}

system.out.print1n(this.title + " = " + this.note);

public synchronized void set(String title,string note) {

this.title = title ;

try i

Thread.sleep(100) ;

}catch (InterruptedException e) {

e.printstackTrace();

}

this.note = note ;

public void setNote(string note) {

this.note = note;

}

public void setTitle(string title) {

this.title = title;

}

public string getNote() {

return note;

}

public string getTitle() {

return title;

暂时先不要

if (x % 2 == ) i

this.data.setTitle("老李");try {

Thread.sleep( 1000) ;

}catch (InterruptedException e) {

e.printstackTrace();

}

this.data. setNote("是个好人");}else i

this.data.setTitle("民族败类");try i

Thread.sleep(200);

}catch (InterruptedException e) i

e.printstackTrace();

}

将上方代码修改为以下方式

for (int x = 0; x < 50; x++) {

if (× % 2 == ) i

this.data.set("老李","是个好人");}else {

this.data.set("民族败类","老方B");

}

}

}

}

T

try {

Thread.sleep(150);

}catch (InterruptedException e) {

e.printstackTrace();

}

system.out.println(this.data.getTitle() + " = " + this.data.getNote())

上方代码修改为 get

this.data.get();

于是现在发现,整个数据的同步得到了很好的解决,但是重复操作的问题严重了

Thread.sleep(50); 这个是取得时间

Thread.sleep(00) ;这是设的延迟

生产快取的慢

所以此代码直解决了数据同步但无法解决交替问题。