Synchronized

1.Synchronized 

synchronized是Java中解决并发问题的一种最常见也是最简单的方法。synchrinzed的作用主要作用有三个:    

(1)确保线程互斥的访问同步代码

(2)保证共享变量的修改能够及时看到

(3)有效解决重排序问题

synchronized总共有三个作用:

(1)修饰普通方法

(2)修饰静态方法

(3)修饰代码块

1.没有同步块的情况

public class SynchronizedTest {

public static void main(String[] args) {

final SynchronizedTest test =new SynchronizedTest();

        new Thread(new Runnable() {

@Override

            public void run() {

test.methodOne();

            }

}).start();

        new Thread(new Runnable() {

@Override

            public void run() {

test.methodTwo();

            }

}).start();

    }

public void methodOne() {

System.out.println("Method One start");

        try {

System.out.println("Method One execute");

            Thread.sleep(3000);

        }catch (Exception e) {

e.printStackTrace();

        }

System.out.println("Method One end");

    }

public void methodTwo() {

System.out.println("Method Two start");

        try {

System.out.println("Method Two execute");

            Thread.sleep(1000);

        }catch (Exception e) {

e.printStackTrace();

        }

System.out.println("Method Two end");

    }

}

执行结果:

Method One start

Method One execute

Method Two start

Method Two execute

Method Two end

Method One end

Process finished with exit code 0

2.对普通方法使用synchronized修饰同步

public class SynchronizedTest {

public static void main(String[] args) {

final SynchronizedTest test =new SynchronizedTest();

        new Thread(new Runnable() {

@Override

            public void run() {

test.methodOne();

            }

}).start();

        new Thread(new Runnable() {

@Override

            public void run() {

test.methodTwo();

            }

}).start();

    }

public synchronized void methodOne() {

System.out.println("Method One start");

        try {

System.out.println("Method One execute");

            Thread.sleep(3000);

        }catch (Exception e) {

e.printStackTrace();

        }

System.out.println("Method One end");

    }

public synchronized void methodTwo() {

System.out.println("Method Two start");

        try {

System.out.println("Method Two execute");

            Thread.sleep(1000);

        }catch (Exception e) {

e.printStackTrace();

        }

System.out.println("Method Two end");

    }

}

执行结果:

Method One start

Method One execute

Method One end

Method Two start

Method Two execute

Method Two end

Process finished with exit code 0

3.使用synchronized修饰静态方法

你可能感兴趣的:(Synchronized)