多线程 有货色不明白
多线程 有东西不明白
刚接触多线程 很多东西很晕,譬如网上这段代码,请教一下:
其中有一段对这段代码的点评:“出现了重复读取的问题,也肯定有重复覆盖的问题”
1.请问为什么会这这样?
2.因为Info的set方法和get方法都加上了synchronized ,所以当又一个线程调用了其中的一个方法时候(比如set),另外一个方法(比如get)也就被这个线程占用,不能被别的线程占用,这样理解对不?
3.不知道为什么会出现这样的运行结果,生产者线程不是已经占用Info的set和get ,然后在循环中一直把名字和年龄改来改去吗?消费者线程为什么还能输出每次生产者线程修改的结果?
这个程序的运行过程究竟是咋样的?谢谢前辈
刚接触多线程 很多东西很晕,譬如网上这段代码,请教一下:
其中有一段对这段代码的点评:“出现了重复读取的问题,也肯定有重复覆盖的问题”
1.请问为什么会这这样?
2.因为Info的set方法和get方法都加上了synchronized ,所以当又一个线程调用了其中的一个方法时候(比如set),另外一个方法(比如get)也就被这个线程占用,不能被别的线程占用,这样理解对不?
3.不知道为什么会出现这样的运行结果,生产者线程不是已经占用Info的set和get ,然后在循环中一直把名字和年龄改来改去吗?消费者线程为什么还能输出每次生产者线程修改的结果?
这个程序的运行过程究竟是咋样的?谢谢前辈
class Info {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public synchronized void set(String name, int age){
this.name=name;
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
this.age=age;
}
public synchronized void get(){
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(this.getName()+"<===>"+this.getAge());
}
private String name = "Rollen";
private int age = 20;
}
/**
* 生产者
* */
class Producer implements Runnable {
private Info info = null;
Producer(Info info) {
this.info = info;
}
public void run() {
boolean flag = false;
for (int i = 0; i < 25; ++i) {
if (flag) {
this.info.set("Rollen", 20);
flag = false;
} else {
this.info.set("ChunGe", 100);