1.修饰代码块
如下,代码块synchronized(object)中是同步的
static int count = 0;
static Object object = new Object();
public void start(){
for(int i=0;i<10;i++){
new Thread(()->{
for(int j=0;j<1000;j++){
synchronized(object){
count++;
}
}
}).start();;
}
}
public static void main(String[] args) throws InterruptedException {
VolatileVisibilitySample sample = new VolatileVisibilitySample();
sample.start();
Thread.sleep(3000);
System.out.println(count);
}
2.修饰非静态方法
如下,方法start中在VolatileVisibilitySample当前的这个对象中是同步的。
public class VolatileVisibilitySample {
static int count = 0;
public synchronized void start(){
for(int j=0;j<1000;j++){
count++;
}
}
public static void main(String[] args) throws InterruptedException {
VolatileVisibilitySample sample = new VolatileVisibilitySample();
for(int i=0;i<10;i++){
new Thread(()->{
sample.start();
}).start();;
}
Thread.sleep(3000);
System.out.println(count);
}
}
注意,修饰非静态方法时,synchronized仅是在当前的类中起到同步作用的,请看下面例子,计算出来的count就是不正确的:
public class VolatileVisibilitySample {
static int count = 0;
public synchronized void start(){
for(int j=0;j<1000;j++){
count++;
}
}
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<10;i++){
new Thread(()->{
VolatileVisibilitySample sample = new VolatileVisibilitySample();
sample.start();
}).start();;
}
Thread.sleep(3000);
System.out.println(count);
}
}
3.修改静态方法
如下,静态方法start中是同步的
public class VolatileVisibilitySample {
static int count = 0;
public static synchronized void start(){
for(int j=0;j<1000;j++){
count++;
}
}
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<10;i++){
new Thread(()->{
start();
}).start();;
}
Thread.sleep(3000);
System.out.println(count);
}
}