定义一个dog类 public class Dog { private String name ; public String getName () { return name ; } public void setName ( String name ) { this . name = name ; } } 定义一个同步对象锁 //同步对象锁 public class SysObject imple
public class Dog {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
定义一个同步对象锁//同步对象锁
public class SysObject implements Runnable {
private Dog dog;
public SysObject(){
if(dog==null){
dog=new Dog();
}
}
public void run(){
Thread current=Thread.currentThread();
synchronized (dog){
for(int i=1;i<10;i++){
System.out.println( "线程"+current.getName()+"在修改dog的名字" );
dog.setName( "卡尔"+ i);
System.out.println( dog.getName() );
try {
Thread.sleep( 1000 );
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
测试类public class test109 {
public static void main(String[] args){
SysObject sysObj=new SysObject();
Thread t0=new Thread( sysObj,"歌谣" );
Thread t1=new Thread( sysObj,"小白" );
Thread t2=new Thread( sysObj,"小红" );
t2.setPriority( Thread.MAX_PRIORITY );
t2.start();
t1.start();
t0.start();
}
}
运行结果