Synchronized 理解

用法:1.同步方法。2.同步静态方法。3同步代码块。

理解Synchronized 的关键是“锁” (原理在最后)

同步代码有“锁”者执行。所谓的锁必须是同一个。静态的方法是该类的.class ,而非静态的或代码块指的是同一个对象。

来说说不同情况下的锁的情形。

一:类中有普通同步方法 

package test;

public class Test {
    public synchronized void fun() {
        System.out.println("fun start");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("fun end");
    }

public static void main(String[] args) {

        Test test = new Test();
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                test.fun();
            }
        });
        t.start();
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                test.fun();
            }
        });
        t2.start();

    }

}

线程同步synchronized理解

显然是同步执行的。就是t线程执行结束,t1才能进度,没有什么异议。

现在做一个改变

线程同步synchronized理解

 1 package test;
 2 
 3 public class Test {
 4     public synchronized void fun() {
 5         System.out.println("fun start");
 6         try {
 7             Thread.sleep(1000);
 8         } catch (InterruptedException e) {
 9             e.printStackTrace();
10         }
11         System.out.println("fun end");
12     }
13 
14     public synchronized void funNoSyc() {
15         System.out.println("funNoSyc start");
16         try {
17             Thread.sleep(1000);
18         } catch (InterruptedException e) {
19             e.printStackTrace();
20         }
21         System.out.println("funNoSyc end");
22     }
23 
24     public static void main(String[] args) {
25 
26         Test test = new Test();
27         Test test1 = new Test();
28         Thread t = new Thread(new Runnable() {
29 
30             @Override
31             public void run() {
32                 test.fun();
33             }
34         });
35         t.start();
36         Thread t2 = new Thread(new Runnable() {
37 
38             @Override
39             public void run() {
40                 test1.fun();
41             }
42         });
43         t2.start();
44 
45     }
46 
47 }
View Code

相关文章: