溫馨提示×

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

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

java線程、進(jìn)程和Synchronized的概念

發(fā)布時(shí)間:2021-09-01 20:59:02 來(lái)源:億速云 閱讀:93 作者:chen 欄目:編程語(yǔ)言

這篇文章主要介紹“java線程、進(jìn)程和Synchronized的概念”,在日常操作中,相信很多人在java線程、進(jìn)程和Synchronized的概念問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”java線程、進(jìn)程和Synchronized的概念”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

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

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

(2)下圖是來(lái)自知乎用戶的解釋:

java線程、進(jìn)程和Synchronized的概念

通過(guò)上述的大致了解,基本知道線程和進(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線程、進(jìn)程和Synchronized的概念

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

(1)繼承Thread,重寫(xiě)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è)線程訪問(wèn)某一個(gè)類(對(duì)象或方法)時(shí),這個(gè)類始終能表現(xiàn)出正確的行為,那么這個(gè)類(對(duì)象或方法)就是線程安全的。

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

說(shuō)明如下:

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

    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 = 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ì)象的不同的鎖,他們互補(bǔ)影響的。

那么,我們?cè)谡5膱?chǎng)景的時(shí)候,肯定是有一種情況的就是,所有的對(duì)象會(huì)對(duì)一個(gè)變量count進(jìn)行操作,那么如何實(shí)現(xiàn)哪?很簡(jiǎn)單就是加static,我們知道,用static修改的方法或者變量,在該類的所有對(duì)象是具有相同的引用的,這樣的話,無(wú)論實(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)我們所需要的場(chǎng)景,同時(shí)也說(shuō)明了,對(duì)于非靜態(tài)static修飾的方法或變量,是一個(gè)對(duì)象一把鎖的。

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

(1)同步:synchronized

同步的概念就是共享,我們要知道“共享”這兩個(gè)字,如果不是共享的資源,就沒(méi)有必要進(jìn)行同步,也就是沒(méi)有必要進(jìn)行加鎖;

同步的目的就是為了線程的安全,其實(shí)對(duì)于線程的安全,需要滿足兩個(gè)最基本的特性:原子性和可見(jiàn)性;

(2)異步:asynchronized

異步的概念就是獨(dú)立,相互之間不受到任何制約,兩者之間沒(méi)有任何關(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()就是異步的方法。

到此,關(guān)于“java線程、進(jìn)程和Synchronized的概念”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

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

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

AI