1.修饰代码块
    如下,代码块synchronized(object)中是同步的

    1. static int count = 0;
    2. static Object object = new Object();
    3. public void start(){
    4. for(int i=0;i<10;i++){
    5. new Thread(()->{
    6. for(int j=0;j<1000;j++){
    7. synchronized(object){
    8. count++;
    9. }
    10. }
    11. }).start();;
    12. }
    13. }
    14. public static void main(String[] args) throws InterruptedException {
    15. VolatileVisibilitySample sample = new VolatileVisibilitySample();
    16. sample.start();
    17. Thread.sleep(3000);
    18. System.out.println(count);
    19. }

    2.修饰非静态方法
    如下,方法start中在VolatileVisibilitySample当前的这个对象中是同步的。

    1. public class VolatileVisibilitySample {
    2. static int count = 0;
    3. public synchronized void start(){
    4. for(int j=0;j<1000;j++){
    5. count++;
    6. }
    7. }
    8. public static void main(String[] args) throws InterruptedException {
    9. VolatileVisibilitySample sample = new VolatileVisibilitySample();
    10. for(int i=0;i<10;i++){
    11. new Thread(()->{
    12. sample.start();
    13. }).start();;
    14. }
    15. Thread.sleep(3000);
    16. System.out.println(count);
    17. }
    18. }

    注意,修饰非静态方法时,synchronized仅是在当前的类中起到同步作用的,请看下面例子,计算出来的count就是不正确的:

    1. public class VolatileVisibilitySample {
    2. static int count = 0;
    3. public synchronized void start(){
    4. for(int j=0;j<1000;j++){
    5. count++;
    6. }
    7. }
    8. public static void main(String[] args) throws InterruptedException {
    9. for(int i=0;i<10;i++){
    10. new Thread(()->{
    11. VolatileVisibilitySample sample = new VolatileVisibilitySample();
    12. sample.start();
    13. }).start();;
    14. }
    15. Thread.sleep(3000);
    16. System.out.println(count);
    17. }
    18. }

    3.修改静态方法
    如下,静态方法start中是同步的

    1. public class VolatileVisibilitySample {
    2. static int count = 0;
    3. public static synchronized void start(){
    4. for(int j=0;j<1000;j++){
    5. count++;
    6. }
    7. }
    8. public static void main(String[] args) throws InterruptedException {
    9. for(int i=0;i<10;i++){
    10. new Thread(()->{
    11. start();
    12. }).start();;
    13. }
    14. Thread.sleep(3000);
    15. System.out.println(count);
    16. }
    17. }