Main:
public class Main { // static volatile int i =0; public static void main(String[] args) {
Person p = new Person("xiaoming"); for(int j=0;j<1000;j++){ new Thread(new Runnable() { @Override public void run() { synchronized (this){ try { p.add(); } catch (InterruptedException e) { throw new RuntimeException(e); } } System.out.println(Person.age+"*******"); } }).start(); } try { new Thread().sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Person.age); }
Person.class:
package pj.imcp;
public class Person {
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String name;
public volatile static int age;
public Person(int age) {
this.age = age;
}
public synchronized void add() throws InterruptedException {
this.age++;
}
}
//当某个变量或方法需要被类的所有实例共享时,可以使用static修饰
//并发3个特性:可见性,有序性,原子性