java多線程之線程,進程和Synchronized概念初解
一、進程與線程的概念
(1)在傳統(tǒng)的操作系統(tǒng)中,程序并不能獨立運行,作為資源分配和獨立運行的基本單位都是進程。
在未配置 OS 的系統(tǒng)中,程序的執(zhí)行方式是順序執(zhí)行,即必須在一個程序執(zhí)行完后,才允許另一個程序執(zhí)行;在多道程序環(huán)境下,則允許多個程序并發(fā)執(zhí)行。程序的這兩種執(zhí)行方式間有著顯著的不同。也正是程序并發(fā)執(zhí)行時的這種特征,才導致了在操作系統(tǒng)中引入進程的概念。
自從在 20 世紀 60 年代人們提出了進程的概念后,在 OS 中一直都是以進程作為能擁有資源和獨立運行的基本單位的。直到 20 世紀 80 年代中期,人們又提出了比進程更小的能獨立運行的基本單位——線程(Threads),試圖用它來提高系統(tǒng)內(nèi)程序并發(fā)執(zhí)行的程度,從而可進一步提高系統(tǒng)的吞吐量。特別是在進入 20 世紀 90 年代后,多處理機系統(tǒng)得到迅速發(fā)展,線程能比進程更好地提高程序的并行執(zhí)行程度,充分地發(fā)揮多處理機的優(yōu)越性,因而在近幾年所推出的多處理機 OS 中也都引入了線程,以改善 OS 的性能。
—–以上摘自《計算機操作系統(tǒng)-湯小丹等編著-3 版》 (下載地址)
(2)下圖是來自知乎用戶的解釋:
通過上述的大致了解,基本知道線程和進程是干什么的了,那么我們下邊給進程和線程總結一下概念:
(3)進程(Process)是計算機中的程序關于某數(shù)據(jù)集合上的一次運行活動,是系統(tǒng)進行資源分配和調(diào)度的基本單位,是操作系統(tǒng)結構的基礎。在早期面向進程設計的計算機結構中,進程是程序的基本執(zhí)行實體;在當代面向線程設計的計算機結構中,進程是線程的容器。程序是指令、數(shù)據(jù)及其組織形式的描述,進程是程序的實體。
(4)線程,有時被稱為輕量級進程(Lightweight Process,LWP),是程序執(zhí)行流的最小單元。線程是程序中一個單一的順序控制流程。進程內(nèi)一個相對獨立的、可調(diào)度的執(zhí)行單元,是系統(tǒng)獨立調(diào)度和分派CPU的基本單位指運行中的程序的調(diào)度單位。在單個程序中同時運行多個線程完成不同的工作,稱為多線程。
(5)進程和線程的關系:
二、Java實現(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(); //線程啟動的正確方式 } }
輸出結果:
Thread-0 Thread-0 Thread-0 ...
另外,要明白啟動線程的是start()方法而不是run()方法,如果用run()方法,那么他就是一個普通的方法執(zhí)行了。
(2)實現(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(); } }
三、線程安全
線程安全概念:當多個線程訪問某一個類(對象或方法)時,這個類始終能表現(xiàn)出正確的行為,那么這個類(對象或方法)就是線程安全的。
線程安全就是多線程訪問時,采用了加鎖機制,當一個線程訪問該類的某個數(shù)據(jù)時,進行保護,其他線程不能進行訪問直到該線程讀取完,其他線程才可使用。不會出現(xiàn)數(shù)據(jù)不一致或者數(shù)據(jù)污染。 線程不安全就是不提供數(shù)據(jù)訪問保護,有可能出現(xiàn)多個線程先后更改數(shù)據(jù)造成所得到的數(shù)據(jù)是臟數(shù)據(jù)。這里的加鎖機制常見的如:synchronized
四、synchronized修飾符
(1)synchronized:可以在任意對象及方法上加鎖,而加鎖的這段代碼稱為“互斥區(qū)”或“臨界區(qū)”。
(2)**不使用**synchronized實例(代碼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(); } }
輸出的一種結果如下:
thread3 count:2 thread4 count:1 thread1 count:2 thread2 count:3 thread5 count:0
可以看到,上述的結果是不正確的,這是因為,多個線程同時操作run()方法,對count進行修改,進而造成錯誤。
(3)**使用**synchronized實例(代碼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(); } }
輸出結果:
thread1 count:4 thread2 count:3 thread3 count:2 thread5 count:1 thread4 count:0
可以看出代碼A和代碼B的區(qū)別就是在run()方法上加上了synchronized修飾。
說明如下:
當多個線程訪問MyThread 的run方法的時候,如果使用了synchronized修飾,那個多線程就會以排隊的方式進行處理(這里排隊是按照CPU分配的先后順序而定的),一個線程想要執(zhí)行synchronized修飾的方法里的代碼,首先是嘗試獲得鎖,如果拿到鎖,執(zhí)行synchronized代碼體的內(nèi)容,如果拿不到鎖的話,這個線程就會不斷的嘗試獲得這把鎖,直到拿到為止,而且多個線程同時去競爭這把鎖,也就是會出現(xiàn)鎖競爭的問題。
五、一個對象有一把鎖!多個線程多個鎖!
何為,一個對象一把鎖,多個線程多個鎖!首先看一下下邊的實例代碼(代碼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(); } }
輸出結果:
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
可以看出,有兩個對象:multiThread1和multiThread2,如果多個對象使用同一把鎖的話,那么上述執(zhí)行的結果就應該是:thread2 tag b, num = -100,因此,是每一個對象擁有該對象的鎖的。
關鍵字synchronized取得的鎖都是對象鎖,而不是把一段代碼或方法當做鎖,所以上述實例代碼C中哪個線程先執(zhí)行synchronized 關鍵字的方法,那個線程就持有該方法所屬對象的鎖,兩個對象,線程獲得的就是兩個不同對象的不同的鎖,他們互補影響的。
那么,我們在正常的場景的時候,肯定是有一種情況的就是,所有的對象會對一個變量count進行操作,那么如何實現(xiàn)哪?很簡單就是加static,我們知道,用static修改的方法或者變量,在該類的所有對象是具有相同的引用的,這樣的話,無論實例化多少對象,調(diào)用的都是一個方法,代碼如下(代碼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(); } }
輸出結果:
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
可以看出,對變量和方法都加上了static修飾,就可以實現(xiàn)我們所需要的場景,同時也說明了,對于非靜態(tài)static修飾的方法或變量,是一個對象一把鎖的。
六、對象鎖的同步和異步
(1)同步:synchronized
同步的概念就是共享,我們要知道“共享”這兩個字,如果不是共享的資源,就沒有必要進行同步,也就是沒有必要進行加鎖;
同步的目的就是為了線程的安全,其實對于線程的安全,需要滿足兩個最基本的特性:原子性和可見性;
(2)異步:asynchronized
異步的概念就是獨立,相互之間不受到任何制約,兩者之間沒有任何關系。
(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()就是異步的方法。
總結
以上就是本文關于java多線程之線程,進程和Synchronized概念初解的全部內(nèi)容,希望對大家有所幫助。如有不足之處,歡迎留言指出,小編會及時回復大家的。
- 簡述Java中進程與線程的關系_動力節(jié)點Java學院整理
- java中進程與線程_三種實現(xiàn)方式總結(必看篇)
- Java多線程并發(fā)執(zhí)行demo代碼實例
- java高并發(fā)之理解進程和線程
- Java多線程高并發(fā)中解決ArrayList與HashSet和HashMap不安全的方案
- java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和Semaphore
- Java的線程與進程以及線程的四種創(chuàng)建方式
- Java并發(fā)編程之volatile與JMM多線程內(nèi)存模型
- Java多線程并發(fā)與并行和線程與進程案例
相關文章
Spring注解@Autowired和@Resource的區(qū)別詳解
這篇文章主要介紹了Spring注解@Autowired和@Resource的區(qū)別詳解,@Autowired與@Resource都可以用來裝配bean,都可以寫在字段或setter方法上,@Resource是JDK提供的注解,默認按照名稱進行裝配,名稱可通過name屬性進行指定,需要的朋友可以參考下2023-12-12Java JVM運行時數(shù)據(jù)區(qū)(Run-Time Data Areas)
運行時數(shù)據(jù)區(qū),是java虛擬機定義的在程序執(zhí)行期間使用的各種運行時的數(shù)據(jù)區(qū),通過JVM運行時數(shù)據(jù)區(qū)圖例給大家展示的很詳細,對JVM 運行時數(shù)據(jù)區(qū)相關知識感興趣的朋友跟隨小編一起看看吧2021-06-06Java PriorityQueue優(yōu)點和缺點面試精講
這篇文章主要為大家介紹了Java面試中PriorityQueue的優(yōu)點和缺點及使用注意詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10