您的位置:首页 > 其它

生產者消費者(解決綫程同步問題)

2017-06-28 20:21 225 查看
這届上幹貨,初學者可以瞭解下!



class Info {
private String name;
private String description;

public synchronized void set(String name, String description) {
this.name = name;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.description = description;
}

public synchronized void get() {

System.out.println(this.name + "---------->" + this.description);
}

}

class Pr implements Runnable {
private  Info info;

public Pr(Info info) {
this.info = info;
}

@Override
public void run() {
for (int i = 0; i < 50; i++) {
if (i % 2 == 0) {
this.info.set("TOM", ":BOY");
} else {
this.info.set("MARY", ":GIRY");
}
}

}
}

class Cr implements Runnable {
private Info info;

public Cr(Info info) {
this.info = info;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
this.info.get();
}

}
}

public class Demo {
public static void main(String[] args) {
Info info = new Info();
Pr pr = new Pr(info);
Cr cr = new Cr(info);

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