為什么要使用Synchronized關(guān)鍵字?為了解決線程高并發(fā)安全問題,共享數(shù)據(jù),多線程共同操作共享數(shù)據(jù),Synchronized可以保證同一時(shí)刻只有一個(gè)線程訪問代碼塊或者方法。
結(jié)論:當(dāng)兩個(gè)線程同時(shí)對(duì)一個(gè)對(duì)象的一個(gè)方法進(jìn)行操作,只有一個(gè)線程能夠搶到鎖。因?yàn)橐粋€(gè)對(duì)象只有一把鎖,一個(gè)線程獲取了該對(duì)象的鎖之后,其他線程無法獲取該對(duì)象的鎖,就不能訪問該對(duì)象的其他synchronized實(shí)例方法,但是可以訪問非synchronized修飾的方法
例題:
1、一個(gè)線程獲取了該對(duì)象的鎖之后,其他線程來訪問其他synchronized實(shí)例方法現(xiàn)象:
public synchronized void method1() {
? ? ? ? System.out.println("Method 1 start");
? ? ? ? try {
? ? ? ? ? ? System.out.println("Method 1 execute");
? ? ? ? ? ? Thread.sleep(3000);
? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? System.out.println("Method 1 end");
? ? }
? ? public synchronized void method2() {
? ? ? ? System.out.println("Method 2 start");
? ? ? ? try {
? ? ? ? ? ? System.out.println("Method 2 execute");
? ? ? ? ? ? Thread.sleep(1000);
? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? System.out.println("Method 2 end");
? ? }
? ? ? ? public static void main(String[] args) {
? ? ? ? ? ? final syncTest test = new syncTest();
? ? ? ? ? ? new Thread(new Runnable() {
? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ? test.method1();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }).start();
? ? ? ? ? ? new Thread(new Runnable() {
? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ? test.method2();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }).start();
? ? ? ? }
輸出結(jié)果:

2、一個(gè)線程獲取了該對(duì)象的鎖之后,其他線程來訪問其他非synchronized實(shí)例方法現(xiàn)象:
去掉②中方法二的synchronized:
public synchronized void method1() {
? ? ? ? System.out.println("Method 1 start");
? ? ? ? try {
? ? ? ? ? ? System.out.println("Method 1 execute");
? ? ? ? ? ? Thread.sleep(3000);
? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? System.out.println("Method 1 end");
? ? }
? ? public void method2() {
? ? ? ? System.out.println("Method 2 start");
? ? ? ? try {
? ? ? ? ? ? System.out.println("Method 2 execute");
? ? ? ? ? ? Thread.sleep(1000);
? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? System.out.println("Method 2 end");
? ? }
? ? ? ? public static void main(String[] args) {
? ? ? ? ? ? final syncTest test = new syncTest();
? ? ? ? ? ? new Thread(new Runnable() {
? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ? test.method1();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }).start();
? ? ? ? ? ? new Thread(new Runnable() {
? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ? test.method2();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }).start();
? ? ? ? }
輸出結(jié)果:

分析:當(dāng)線程1還在執(zhí)行時(shí),線程2也執(zhí)行了,所以當(dāng)其他線程來訪問非synchronized修飾的方法時(shí)是可以訪問的