/**
*
*
* 模拟一个场景:Meten和Eric同时喜欢上了一个妹妹Janet,这两个人就开始追了Eric追Janet的方式是牺牲色相,他追了50次,
* Meten追Janet的方式用的是金钱, 他追了30次
* 在追的过程中,如果打印meten的追女孩子的方式有一次是色相,那么这个程序就错了
* 或者如果打印Eric追女孩子的方式有一次是金钱,那么这个程序就错了
* 提醒:共享数据,但不共享代码
* @author 够潮
*
*/
public class Demo15 {
/**
* 共享数据的时候,为了防止出现脏数据,应加锁
*/
public static void main(String[] args) {
Janet j = new Janet();
Eric e = new Eric(j,"Eric");
Meten m = new Meten(j,"Meten");
e.start();
m.start();
}
}
class Janet {
/**
* 共享的数据
*/
String msg;
public String getMsg() {
return msg;
}
/**
* 对共享的数据进行加锁
* @param msg
*/
public synchronized void setMsg(String msg) {
this.msg = msg;
System.out.println(Thread.currentThread().getName()+"说:"+this.getMsg());
}
}
class Meten extends Thread{
Janet j;
public Meten(Janet j, String name) {
super(name);
this.j = j;
}
public void run(){
for( int i = 0; i < 30; i++ ){
this.j.setMsg("使用金钱");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Eric extends Thread{
Janet j;
public Eric(Janet j,String name) {
super(name);
this.j = j;
}
public void run(){
for( int i = 0; i < 50; i++ ){
this.j.setMsg("牺牲色相");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}