Java多線程基本使用
一、概念
1.進(jìn)程
1.1進(jìn)程:是一個(gè)正在進(jìn)行中的程序,每一個(gè)進(jìn)程執(zhí)行都有一個(gè)執(zhí)行順序,該順序是一個(gè)執(zhí)行路徑,或者叫一個(gè)控制單元。
1.2線程:就是進(jìn)程中一個(gè)獨(dú)立的控制單元,線程在控制著進(jìn)程的執(zhí)行,一個(gè)進(jìn)程中至少有一個(gè)線程。
1.3舉例java VM:
Java VM啟動(dòng)的時(shí)候會(huì)有一個(gè)進(jìn)程java.exe,該進(jìn)程中至少有一個(gè)線程在負(fù)責(zé)java程序的運(yùn)行,而且這個(gè)線程運(yùn)行的代碼存在于main方法中,該線程稱之為主線程。擴(kuò)展:其實(shí)更細(xì)節(jié)說明jvm,jvm啟動(dòng)不止一個(gè)線程,還有負(fù)責(zé)垃圾回收機(jī)制的線程
2.多線程存在的意義:提高執(zhí)行效率
二、多線程的創(chuàng)建
1.多線程創(chuàng)建的***種方式,繼承Thread類
1.1定義類繼承Thread,復(fù)寫Thread類中的run方法是為了將自定義的代碼存儲(chǔ)到run方法中,讓線程運(yùn)行
1.2調(diào)用線程的start方法,該方法有兩個(gè)作用:?jiǎn)?dòng)線程,調(diào)用run方法
1.3多線程運(yùn)行的時(shí)候,運(yùn)行結(jié)果每一次都不同,因?yàn)槎鄠€(gè)線程都獲取cpu的執(zhí)行權(quán),cpu執(zhí)行到誰,誰就運(yùn)行,明確一點(diǎn),在某一個(gè)時(shí)刻,只能有一個(gè)程序在運(yùn)行。(多核除外),cpu在做著快速的切換,以到達(dá)看上去是同時(shí)運(yùn)行的效果。我們可以形象把多線程的運(yùn)行行為在互搶cpu的執(zhí)行權(quán)。這就是多線程的一個(gè)特性,隨機(jī)性。誰搶到,誰執(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)建一個(gè)線程
- d.start();//開啟線程,并執(zhí)行該線程的run方法
- d.run(); //僅僅是對(duì)象調(diào)用方法,而線程創(chuàng)建了但并沒有運(yùn)行
- for (int x = 0; x < 60; x++) {
- System.out.println("Hello World---"+x);
- }
- }
- }
2 創(chuàng)建多線程的第二種方式,步驟:
2.1定義類實(shí)現(xiàn)Runnable接口
2.2覆蓋Runnable接口中的run方法:將線程要運(yùn)行的代碼存放到run方法中
2.3.通過Thread類建立線程對(duì)象
2.4.將Runnable接口的子類對(duì)象作為實(shí)際參數(shù)傳遞給Thread類的構(gòu)造函數(shù)
為什么要將Runnable接口的子類對(duì)象傳遞給Thread的構(gòu)造函數(shù):因?yàn)樽远x的run方法所屬的對(duì)象是Runnable接口的子類對(duì)象,所以要讓線程去執(zhí)行指定對(duì)象的run方法,就必須明確該run方法的所屬對(duì)象
2.5.調(diào)用Thread類的start方法開啟線程并調(diào)用Runnable接口子類的方法
- /*
- * 需求:簡(jiǎn)易買票程序,多個(gè)窗口同時(shí)賣票
- */
- 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.實(shí)現(xiàn)方式和繼承方式有什么區(qū)別
3.1.實(shí)現(xiàn)方式避免了單繼承的局限性,在定義線程時(shí)建議使用實(shí)現(xiàn)方式
3.2.繼承Thread類:線程代碼存放在Thread子類run方法中
3.3.實(shí)現(xiàn)Runnable:線程代碼存放在接口的子類run方法中
4.多線程-run和start的特點(diǎn)
4.1為什么要覆蓋run方法呢:
Thread類用于描述線程,該類定義了一個(gè)功能,用于存儲(chǔ)線程要運(yùn)行的代碼,該存儲(chǔ)功能就是run方法,也就是說該Thread類中的run方法,用于存儲(chǔ)線程要運(yùn)行的代碼
5.多線程運(yùn)行狀態(tài)
創(chuàng)建線程-運(yùn)行---sleep()/wait()--凍結(jié)---notify()---喚醒
創(chuàng)建線程-運(yùn)行---stop()—消亡
創(chuàng)建線程-運(yùn)行---沒搶到cpu執(zhí)行權(quán)—臨時(shí)凍結(jié)
6.獲取線程對(duì)象及其名稱
6.1.線程都有自己默認(rèn)的名稱,編號(hào)從0開始
6.2.static Thread currentThread():獲取當(dāng)前線程對(duì)象
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)多條語句在操作同一個(gè)線程共享數(shù)據(jù)時(shí),一個(gè)線程對(duì)多條語句只執(zhí)行了一部分,還沒有執(zhí)行完,另一個(gè)線程參與進(jìn)來執(zhí)行,導(dǎo)致共享數(shù)據(jù)的錯(cuò)誤
1.2.解決辦法:對(duì)多條操作共享數(shù)據(jù)的語句,只能讓一個(gè)線程都執(zhí)行完,在執(zhí)行過程中,其他線程不可以參與執(zhí)行
1.3.java對(duì)于多線程的安全問題提供了專業(yè)的解決方式,就是同步代碼塊:
Synchronized(對(duì)象){需要被同步的代碼},對(duì)象如同鎖,持有鎖的線程可以在同步中執(zhí)行,沒有持有鎖的線程即使獲取cpu執(zhí)行權(quán),也進(jìn)不去,因?yàn)闆]有獲取鎖
2.同步的前提:
2.1.必須要有2個(gè)或者2個(gè)以上線程
2.2.必須是多個(gè)線程使用同一個(gè)鎖
2.3.好處是解決了多線程的安全問題
2.4.弊端是多個(gè)線程需要判斷鎖,較消耗資源
2.5.同步函數(shù)
定義同步函數(shù),在方法錢用synchronized修飾即可
- /*
- * 需求:
- * 銀行有一個(gè)金庫(kù),有兩個(gè)儲(chǔ)戶分別存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ù)需要被對(duì)象調(diào)用,那么函數(shù)都有一個(gè)所屬對(duì)象引用,就是this.,所以同步函數(shù)使用的鎖是this
6.2.靜態(tài)函數(shù)的鎖是class對(duì)象
靜態(tài)進(jìn)內(nèi)存時(shí),內(nèi)存中沒有本類對(duì)象,但是一定有該類對(duì)應(yīng)的字節(jié)碼文件對(duì)象,類名.class,該對(duì)象的類型是Class
6.3.靜態(tài)的同步方法,使用的鎖是該方法所在類的字節(jié)碼文件對(duì)象,類名.class
- /*
- * 需求:簡(jiǎn)��買票程序,多個(gè)窗口同時(shí)賣票
- */
- 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ū)別:懶漢式能延遲實(shí)例的加載,如果多線程訪問時(shí),懶漢式會(huì)出現(xiàn)安全問題,可以使用同步來解決,用同步函數(shù)和同步代碼都可以,但是比較低效,用雙重判斷的形式能解決低效的問題,加同步的時(shí)候使用的鎖是該類鎖屬的字節(jié)碼文件對(duì)象
- /*
- * 單例模式
- */
- //餓漢式
- 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.多線程-死鎖
同步中嵌套同步會(huì)出現(xiàn)死鎖
- /*
- * 需求:簡(jiǎn)易買票程序,多個(gè)窗口同時(shí)賣票
- */
- 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();
- }
- }