溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java線程安全和鎖Synchronized知識(shí)點(diǎn)詳解

發(fā)布時(shí)間:2020-08-27 16:25:56 來源:腳本之家 閱讀:123 作者:江彩 欄目:編程語言

一、進(jìn)程與線程的概念

(1)在傳統(tǒng)的操作系統(tǒng)中,程序并不能獨(dú)立運(yùn)行,作為資源分配和獨(dú)立運(yùn)行的基本單位都是進(jìn)程。

在未配置 OS 的系統(tǒng)中,程序的執(zhí)行方式是順序執(zhí)行,即必須在一個(gè)程序執(zhí)行完后,才允許另一個(gè)程序執(zhí)行;在多道程序環(huán)境下,則允許多個(gè)程序并發(fā)執(zhí)行。程序的這兩種執(zhí)行方式間有著顯著的不同。也正是程序并發(fā)執(zhí)行時(shí)的這種特征,才導(dǎo)致了在操作系統(tǒng)中引入進(jìn)程的概念。

自從在 20 世紀(jì) 60 年代人們提出了進(jìn)程的概念后,在 OS 中一直都是以進(jìn)程作為能擁有資源和獨(dú)立運(yùn)行的基本單位的。直到 20 世紀(jì) 80 年代中期,人們又提出了比進(jìn)程更小的能獨(dú)立運(yùn)行的基本單位——線程(Thread),試圖用它來提高系統(tǒng)內(nèi)程序并發(fā)執(zhí)行的程度,從而可進(jìn)一步提高系統(tǒng)的吞吐量。特別是在進(jìn)入 20 世紀(jì) 90 年代后,多處理機(jī)系統(tǒng)得到迅速發(fā)展,線程能比進(jìn)程更好地提高程序的并行執(zhí)行程度,充分地發(fā)揮多處理機(jī)的優(yōu)越性,因而在近幾年所推出的多處理機(jī) OS 中也都引入了線程,以改善 OS 的性能。

(2)下圖是來自知乎用戶的解釋:Java線程安全和鎖Synchronized概念

通過上述的大致了解,基本知道線程和進(jìn)程是干什么的了,那么我們下邊給進(jìn)程和線程總結(jié)一下概念:

(3)進(jìn)程(Process)是計(jì)算機(jī)中的程序關(guān)于某數(shù)據(jù)集合上的一次運(yùn)行活動(dòng),是系統(tǒng)進(jìn)行資源分配和調(diào)度的基本單位,是操作系統(tǒng)結(jié)構(gòu)的基礎(chǔ)。在早期面向進(jìn)程設(shè)計(jì)的計(jì)算機(jī)結(jié)構(gòu)中,進(jìn)程是程序的基本執(zhí)行實(shí)體;在當(dāng)代面向線程設(shè)計(jì)的計(jì)算機(jī)結(jié)構(gòu)中,進(jìn)程是線程的容器。程序是指令、數(shù)據(jù)及其組織形式的描述,進(jìn)程是程序的實(shí)體。

(4)線程,有時(shí)被稱為輕量級(jí)進(jìn)程(Lightweight Process,LWP),是程序執(zhí)行流的最小單元。線程是程序中一個(gè)單一的順序控制流程。進(jìn)程內(nèi)一個(gè)相對(duì)獨(dú)立的、可調(diào)度的執(zhí)行單元,是系統(tǒng)獨(dú)立調(diào)度和分派CPU的基本單位指運(yùn)行中的程序的調(diào)度單位。在單個(gè)程序中同時(shí)運(yùn)行多個(gè)線程完成不同的工作,稱為多線程。

(5)進(jìn)程和線程的關(guān)系:
Java線程安全和鎖Synchronized概念

二、Java實(shí)現(xiàn)多線程方式

(1)繼承Thread,重寫run()方法

public class MyThread extends Thread {

@Override
public void run() {
  while (true) {
    System.out.println(this.currentThread().getName());
  }
}

public static void main(String[] args) {
  MyThread thread = new MyThread();
  thread.start(); //線程啟動(dòng)的正確方式
}
}

輸出結(jié)果:

Thread-0
Thread-0
Thread-0
...

另外,要明白啟動(dòng)線程的是start()方法而不是run()方法,如果用run()方法,那么他就是一個(gè)普通的方法執(zhí)行了。

(2)實(shí)現(xiàn)Runable接口

public class MyRunnable implements Runnable {

@Override
public void run() {
  System.out.println("123");
}

public static void main(String[] args) {
  MyRunnable myRunnable = new MyRunnable();
  Thread thread = new Thread(myRunnable, "t1");
  thread.start();
}
}

三、線程安全

線程安全概念:當(dāng)多個(gè)線程訪問某一個(gè)類(對(duì)象或方法)時(shí),這個(gè)類始終能表現(xiàn)出正確的行為,那么這個(gè)類(對(duì)象或方法)就是線程安全的。

線程安全就是多線程訪問時(shí),采用了加鎖機(jī)制,當(dāng)一個(gè)線程訪問該類的某個(gè)數(shù)據(jù)時(shí),進(jìn)行保護(hù),其他線程不能進(jìn)行訪問直到該線程讀取完,其他線程才可使用。不會(huì)出現(xiàn)數(shù)據(jù)不一致或者數(shù)據(jù)污染。 線程不安全就是不提供數(shù)據(jù)訪問保護(hù),有可能出現(xiàn)多個(gè)線程先后更改數(shù)據(jù)造成所得到的數(shù)據(jù)是臟數(shù)據(jù)。這里的加鎖機(jī)制常見的如:synchronized

四、synchronized修飾符

(1)synchronized:可以在任意對(duì)象及方法上加鎖,而加鎖的這段代碼稱為“互斥區(qū)”或“臨界區(qū)”。

(2)不使用synchronized實(shí)例(代碼A):

public class MyThread extends Thread {

private int count = 5;

@Override
public void run() {
  count--;
  System.out.println(this.currentThread().getName() + " count:" + count);
}

public static void main(String[] args) {
  MyThread myThread = new MyThread();
  Thread thread1 = new Thread(myThread, "thread1");
  Thread thread2 = new Thread(myThread, "thread2");
  Thread thread3 = new Thread(myThread, "thread3");
  Thread thread4 = new Thread(myThread, "thread4");
  Thread thread5 = new Thread(myThread, "thread5");
  thread1.start();
  thread2.start();
  thread3.start();
  thread4.start();
  thread5.start();
}
}

輸出的一種結(jié)果如下:

thread3 count:2
thread4 count:1
thread1 count:2
thread2 count:3
thread5 count:0

可以看到,上述的結(jié)果是不正確的,這是因?yàn)椋鄠€(gè)線程同時(shí)操作run()方法,對(duì)count進(jìn)行修改,進(jìn)而造成錯(cuò)誤。

(3)使用synchronized實(shí)例(代碼B):

public class MyThread extends Thread {

private int count = 5;

@Override
public synchronized void run() {
  count--;
  System.out.println(this.currentThread().getName() + " count:" + count);
}

public static void main(String[] args) {
  MyThread myThread = new MyThread();
  Thread thread1 = new Thread(myThread, "thread1");
  Thread thread2 = new Thread(myThread, "thread2");
  Thread thread3 = new Thread(myThread, "thread3");
  Thread thread4 = new Thread(myThread, "thread4");
  Thread thread5 = new Thread(myThread, "thread5");
  thread1.start();
  thread2.start();
  thread3.start();
  thread4.start();
  thread5.start();
}
}

輸出結(jié)果:

thread1 count:4
thread2 count:3
thread3 count:2
thread5 count:1
thread4 count:0

可以看出代碼A和代碼B的區(qū)別就是在run()方法上加上了synchronized修飾。

說明如下:
當(dāng)多個(gè)線程訪問MyThread 的run方法的時(shí)候,如果使用了synchronized修飾,那個(gè)多線程就會(huì)以排隊(duì)的方式進(jìn)行處理(這里排隊(duì)是按照CPU分配的先后順序而定的),一個(gè)線程想要執(zhí)行synchronized修飾的方法里的代碼,首先是嘗試獲得鎖,如果拿到鎖,執(zhí)行synchronized代碼體的內(nèi)容,如果拿不到鎖的話,這個(gè)線程就會(huì)不斷的嘗試獲得這把鎖,直到拿到為止,而且多個(gè)線程同時(shí)去競爭這把鎖,也就是會(huì)出現(xiàn)鎖競爭的問題。

五、一個(gè)對(duì)象有一把鎖!多個(gè)線程多個(gè)鎖!

何為,一個(gè)對(duì)象一把鎖,多個(gè)線程多個(gè)鎖!首先看一下下邊的實(shí)例代碼(代碼C):

public class MultiThread {

private int num = 200;

public synchronized void printNum(String threadName, String tag) {
  if (tag.equals("a")) {
    num = num - 100;
    System.out.println(threadName + " tag a,set num over!");
  } else {
    num = num - 200;
    System.out.println(threadName + " tag b,set num over!");
  }
  System.out.println(threadName + " tag " + tag + ", num = " + num);
}

public static void main(String[] args) throws InterruptedException {
  final MultiThread multiThread1 = new MultiThread();
  final MultiThread multiThread2 = new MultiThread();

  new Thread(new Runnable() {
    public void run() {
      multiThread1.printNum("thread1", "a");
    }
  }).start();

  new Thread(new Runnable() {
    public void run() {
      multiThread2.printNum("thread2", "b");
    }
  }).start();
}
}

輸出結(jié)果:

thread1 tag a,set num over!
thread1 tag a, num = 100
thread2 tag b,set num over!
thread2 tag b, num = 0

可以看出,有兩個(gè)對(duì)象:multiThread1和multiThread2,如果多個(gè)對(duì)象使用同一把鎖的話,那么上述執(zhí)行的結(jié)果就應(yīng)該是:thread2 tag b, num = -100,因此,是每一個(gè)對(duì)象擁有該對(duì)象的鎖的。

關(guān)鍵字synchronized取得的鎖都是對(duì)象鎖,而不是把一段代碼或方法當(dāng)做鎖,所以上述實(shí)例代碼C中哪個(gè)線程先執(zhí)行synchronized 關(guān)鍵字的方法,那個(gè)線程就持有該方法所屬對(duì)象的鎖,兩個(gè)對(duì)象,線程獲得的就是兩個(gè)不同對(duì)象的不同的鎖,他們互不影響的。

那么,我們?cè)谡5膱鼍暗臅r(shí)候,肯定是有一種情況的就是,所有的對(duì)象會(huì)對(duì)一個(gè)變量count進(jìn)行操作,那么如何實(shí)現(xiàn)哪?很簡單就是加static,我們知道,用static修改的方法或者變量,在該類的所有對(duì)象是具有相同的引用的,這樣的話,無論實(shí)例化多少對(duì)象,調(diào)用的都是一個(gè)方法,代碼如下(代碼D):

public class MultiThread {

private static int num = 200;

public static synchronized void printNum(String threadName, String tag) {
  if (tag.equals("a")) {
    num = num - 100;
    System.out.println(threadName + " tag a,set num over!");
  } else {
    num = num - 200;
    System.out.println(threadName + " tag b,set num over!");
  }
  System.out.println(threadName + " tag " + tag + ", num = " + num);
}

public static void main(String[] args) throws InterruptedException {
  final MultiThread multiThread1 = new MultiThread();
  final MultiThread multiThread2 = new MultiThread();

  new Thread(new Runnable() {
    public void run() {
      multiThread1.printNum("thread1", "a");
    }
  }).start();

  Thread.sleep(5000);
  System.out.println("等待5秒,確保thread1已經(jīng)執(zhí)行完畢!");

  new Thread(new Runnable() {
    public void run() {
      multiThread2.printNum("thread2", "b");
    }
  }).start();
}
}

輸出結(jié)果:

thread1 tag a,set num over!
thread1 tag a, num = 100

等待5秒,確保thread1已經(jīng)執(zhí)行完畢!

thread2 tag b,set num over!
thread2 tag b, num = -100

可以看出,對(duì)變量和方法都加上了static修飾,就可以實(shí)現(xiàn)我們所需要的場景,同時(shí)也說明了,對(duì)于非靜態(tài)static修飾的方法或變量,是一個(gè)對(duì)象一把鎖的。

六、對(duì)象鎖的同步和異步

(1)同步:synchronized
同步的概念就是共享,我們要知道“共享”這兩個(gè)字,如果不是共享的資源,就沒有必要進(jìn)行同步,也就是沒有必要進(jìn)行加鎖;
同步的目的就是為了線程的安全,其實(shí)對(duì)于線程的安全,需要滿足兩個(gè)最基本的特性:原子性和可見性;

(2)異步:asynchronized
異步的概念就是獨(dú)立,相互之間不受到任何制約,兩者之間沒有任何關(guān)系。

(3)示例代碼:

public class MyObject {

public void method() {
  System.out.println(Thread.currentThread().getName());
}

public static void main(String[] args) {
  final MyObject myObject = new MyObject();

  Thread t1 = new Thread(new Runnable() {
    public void run() {
      myObject.method();
    }
  }, "t1");

  Thread t2 = new Thread(new Runnable() {
    public void run() {
      myObject.method();
    }
  }, "t2");

  t1.start();
  t2.start();
}
}

上述代碼中method()就是異步的方法,同時(shí)感謝大家對(duì)億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI