Java多線程基本使用
一、概念
1.進程
1.1進程:是一個正在進行中的程序,每一個進程執(zhí)行都有一個執(zhí)行順序,該順序是一個執(zhí)行路徑,或者叫一個控制單元。
1.2線程:就是進程中一個獨立的控制單元,線程在控制著進程的執(zhí)行,一個進程中至少有一個線程。
1.3舉例java VM:
Java VM啟動的時候會有一個進程java.exe,該進程中至少有一個線程在負責(zé)java程序的運行,而且這個線程運行的代碼存在于main方法中,該線程稱之為主線程。擴展:其實更細節(jié)說明jvm,jvm啟動不止一個線程,還有負責(zé)垃圾回收機制的線程
2.多線程存在的意義:提高執(zhí)行效率
二、多線程的創(chuàng)建
1.多線程創(chuàng)建的***種方式,繼承Thread類
1.1定義類繼承Thread,復(fù)寫Thread類中的run方法是為了將自定義的代碼存儲到run方法中,讓線程運行
1.2調(diào)用線程的start方法,該方法有兩個作用:啟動線程,調(diào)用run方法
1.3多線程運行的時候,運行結(jié)果每一次都不同,因為多個線程都獲取cpu的執(zhí)行權(quán),cpu執(zhí)行到誰,誰就運行,明確一點,在某一個時刻,只能有一個程序在運行。(多核除外),cpu在做著快速的切換,以到達看上去是同時運行的效果。我們可以形象把多線程的運行行為在互搶cpu的執(zhí)行權(quán)。這就是多線程的一個特性,隨機性。誰搶到,誰執(zhí)行,至于執(zhí)行多久,cpu說了算。
- public class Demo extends Thread{
- public void run(){
- for (int x = 0; x < 60; x++) {
- System.out.println(this.getName()+"demo run---"+x);
- }
- }
- public static void main(String[] args) {
- Demo d=new Demo();//創(chuàng)建一個線程
- d.start();//開啟線程,并執(zhí)行該線程的run方法
- d.run(); //僅僅是對象調(diào)用方法,而線程創(chuàng)建了但并沒有運行
- for (int x = 0; x < 60; x++) {
- System.out.println("Hello World---"+x);
- }
- }
- }
2 創(chuàng)建多線程的第二種方式,步驟:
2.1定義類實現(xiàn)Runnable接口
2.2覆蓋Runnable接口中的run方法:將線程要運行的代碼存放到run方法中
2.3.通過Thread類建立線程對象
2.4.將Runnable接口的子類對象作為實際參數(shù)傳遞給Thread類的構(gòu)造函數(shù)
為什么要將Runnable接口的子類對象傳遞給Thread的構(gòu)造函數(shù):因為自定義的run方法所屬的對象是Runnable接口的子類對象,所以要讓線程去執(zhí)行指定對象的run方法,就必須明確該run方法的所屬對象
2.5.調(diào)用Thread類的start方法開啟線程并調(diào)用Runnable接口子類的方法
- /*
- * 需求:簡易買票程序,多個窗口同時賣票
- */
- public class Ticket implements Runnable {
- private static int tick = 100;
- Object obj = new Object();
- boolean flag=true;
- public void run() {
- if(flag){
- while (true) {
- synchronized (Ticket.class) {
- if (tick > 0) {
- System.out.println(Thread.currentThread().getName()
- + "code:" + tick--);
- }
- }
- }
- }else{
- while(true){
- show();
- }
- }
- }
- public static synchronized void show() {
- if (tick > 0) {
- System.out.println(Thread.currentThread().getName() + "show:"
- + tick--);
- }
- }
- }
- class ThisLockDemo {
- public static void main(String[] args) {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO: handle exception
- }
- t.flag=false;
- Thread t2 = new Thread(t);
- //Thread t3 = new Thread(t);
- //Thread t4 = new Thread(t);
- t1.start();
- t2.start();
- //t3.start();
- //t4.start();
- }
- }
3.實現(xiàn)方式和繼承方式有什么區(qū)別
3.1.實現(xiàn)方式避免了單繼承的局限性,在定義線程時建議使用實現(xiàn)方式
3.2.繼承Thread類:線程代碼存放在Thread子類run方法中
3.3.實現(xiàn)Runnable:線程代碼存放在接口的子類run方法中
4.多線程-run和start的特點
4.1為什么要覆蓋run方法呢:
Thread類用于描述線程,該類定義了一個功能,用于存儲線程要運行的代碼,該存儲功能就是run方法,也就是說該Thread類中的run方法,用于存儲線程要運行的代碼
5.多線程運行狀態(tài)
創(chuàng)建線程-運行---sleep()/wait()--凍結(jié)---notify()---喚醒
創(chuàng)建線程-運行---stop()—消亡
創(chuàng)建線程-運行---沒搶到cpu執(zhí)行權(quán)—臨時凍結(jié)
6.獲取線程對象及其名稱
6.1.線程都有自己默認(rèn)的名稱,編號從0開始
6.2.static Thread currentThread():獲取當(dāng)前線程對象
6.3.getName():獲取線程名稱
6.4.設(shè)置線程名稱:setName()或者使用構(gòu)造函數(shù)
- public class Test extends Thread{
- Test(String name){
- super(name);
- }
- public void run(){
- for (int x = 0; x < 60; x++) {
- System.out.println((Thread.currentThread()==this)+"..."+this.getName()+" run..."+x);
- }
- }
- }
- class ThreadTest{
- public static void main(String[] args) {
- Test t1=new Test("one---");
- Test t2=new Test("two+++");
- t1.start();
- t2.start();
- t1.run();
- t2.run();
- for (int x = 0; x < 60; x++) {
- System.out.println("main----"+x);
- }
- }
- }
三、多線程的安全問題
1.多線程出現(xiàn)安全問題的原因:
1.1.當(dāng)多條語句在操作同一個線程共享數(shù)據(jù)時,一個線程對多條語句只執(zhí)行了一部分,還沒有執(zhí)行完,另一個線程參與進來執(zhí)行,導(dǎo)致共享數(shù)據(jù)的錯誤
1.2.解決辦法:對多條操作共享數(shù)據(jù)的語句,只能讓一個線程都執(zhí)行完,在執(zhí)行過程中,其他線程不可以參與執(zhí)行
1.3.java對于多線程的安全問題提供了專業(yè)的解決方式,就是同步代碼塊:
Synchronized(對象){需要被同步的代碼},對象如同鎖,持有鎖的線程可以在同步中執(zhí)行,沒有持有鎖的線程即使獲取cpu執(zhí)行權(quán),也進不去,因為沒有獲取鎖
2.同步的前提:
2.1.必須要有2個或者2個以上線程
2.2.必須是多個線程使用同一個鎖
2.3.好處是解決了多線程的安全問題
2.4.弊端是多個線程需要判斷鎖,較消耗資源
2.5.同步函數(shù)
定義同步函數(shù),在方法錢用synchronized修飾即可
- /*
- * 需求:
- * 銀行有一個金庫,有兩個儲戶分別存300元,每次存100元,存3次
- * 目的:該程序是否有安全問題,如果有,如何解決
- * 如何找問題:
- * 1.明確哪些代碼是多線程代碼
- * 2.明確共享數(shù)據(jù)
- * 3.明確多線程代碼中哪些語句是操作共享數(shù)據(jù)的
- */
- public class Bank {
- private int sum;
- Object obj = new Object();
- //定義同步函數(shù),在方法錢用synchronized修飾即可
- public synchronized void add(int n) {
- //synchronized (obj) {
- sumsum = sum + n;
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("sum=" + sum);
- //}
- }
- }
- class Cus implements Runnable {
- private Bank b = new Bank();
- public void run() {
- for (int x = 0; x < 3; x++) {
- b.add(100);
- }
- }
- }
- class BankDemo {
- public static void main(String[] args) {
- Cus c = new Cus();
- Thread t1 = new Thread(c);
- Thread t2 = new Thread(c);
- t1.start();
- t2.start();
- }
- }
6.同步的鎖
6.1函數(shù)需要被對象調(diào)用,那么函數(shù)都有一個所屬對象引用,就是this.,所以同步函數(shù)使用的鎖是this
6.2.靜態(tài)函數(shù)的鎖是class對象
靜態(tài)進內(nèi)存時,內(nèi)存中沒有本類對象,但是一定有該類對應(yīng)的字節(jié)碼文件對象,類名.class,該對象的類型是Class
6.3.靜態(tài)的同步方法,使用的鎖是該方法所在類的字節(jié)碼文件對象,類名.class
- /*
- * 需求:簡��買票程序,多個窗口同時賣票
- */
- public class Ticket implements Runnable {
- private static int tick = 100;
- Object obj = new Object();
- boolean flag=true;
- public void run() {
- if(flag){
- while (true) {
- synchronized (Ticket.class) {
- if (tick > 0) {
- System.out.println(Thread.currentThread().getName()
- + "code:" + tick--);
- }
- }
- }
- }else{
- while(true){
- show();
- }
- }
- }
- public static synchronized void show() {
- if (tick > 0) {
- System.out.println(Thread.currentThread().getName() + "show:"
- + tick--);
- }
- }
- }
- class ThisLockDemo {
- public static void main(String[] args) {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO: handle exception
- }
- t.flag=false;
- Thread t2 = new Thread(t);
- //Thread t3 = new Thread(t);
- //Thread t4 = new Thread(t);
- t1.start();
- t2.start();
- //t3.start();
- //t4.start();
- }
- }
7.多線程,單例模式-懶漢式
懶漢式與餓漢式的區(qū)別:懶漢式能延遲實例的加載,如果多線程訪問時,懶漢式會出現(xiàn)安全問題,可以使用同步來解決,用同步函數(shù)和同步代碼都可以,但是比較低效,用雙重判斷的形式能解決低效的問題,加同步的時候使用的鎖是該類鎖屬的字節(jié)碼文件對象
- /*
- * 單例模式
- */
- //餓漢式
- public class Single {
- private static final Single s=new Single();
- private Single(){}
- public static Single getInstance(){
- return s;
- }
- }
- //懶漢式
- class Single2{
- private static Single2 s2=null;
- private Single2(){}
- public static Single2 getInstance(){
- if(s2==null){
- synchronized(Single2.class){
- if(s2==null){
- s2=new Single2();
- }
- }
- }
- return s2;
- }
- }
- class SingleDemo{
- public static void main(String[] args) {
- System.out.println("Hello World");
- }
- }
8.多線程-死鎖
同步中嵌套同步會出現(xiàn)死鎖
- /*
- * 需求:簡易買票程序,多個窗口同時賣票
- */
- public class DeadTest implements Runnable {
- private boolean flag;
- DeadTest(boolean flag) {
- this.flag = flag;
- }
- public void run() {
- if (flag) {
- synchronized(MyLock.locka){
- System.out.println("if locka");
- synchronized(MyLock.lockb){
- System.out.println("if lockb");
- }
- }
- } else {
- synchronized(MyLock.lockb){
- System.out.println("else lockb");
- synchronized(MyLock.locka){
- System.out.println("else locka");
- }
- }
- }
- }
- }
- class MyLock{
- static Object locka=new Object();
- static Object lockb=new Object();
- }
- class DeadLockDemo {
- public static void main(String[] args) {
- Thread t1 = new Thread(new DeadTest(true));
- Thread t2 = new Thread(new DeadTest(false));
- t1.start();
- t2.start();
- }
- }