single thread execution主要思想是:在同一时刻,对于某一共享资源,只能有一个人访问,即资源同步。
package gate;
public class Person {
private String name;
private String address;
public synchronized void setNameAddress(String name,String address){
this.name = name;
this.address = address;
check();
}
private void check(){
if(!name.equals(address)){
System.out.println("problem:"+name+","+address);
}
}
}
/*****************************/
package gate;
public class RunThread extends Thread {
private Person person;
private String name;
private String address;
public RunThread(Person person,String name,String address){
this.person =person;
this.name =name;
this.address =address;
}
public void run(){
while(true){
person.setNameAddress(name,address);
}
}
}
/*******************************/
package gate;
public class Test {
public static void main(String[] args) {
Person person = new Person();
new RunThread(person,"345","345").start();
new RunThread(person,"456","456").start();
}
}
参与者如下:
共享资源(
Person ),资源利用者
(RunThread)
对于共享资源中的线程非安全方法需要加入锁机制(synchronized或者ReentrantLock
)进行同步,确保在某个时间点只有一个线程在访问该方法。
适应的时机:
多线程环境(废话),资源共享(又是废话),资源的状态发生变化(状态不会变化的对象线程安全的)