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