1、多線程
要使用多線程必須有一個(gè)前提,有一個(gè)線程的執(zhí)行主類。從多線程開始,Java正式進(jìn)入到應(yīng)用部分,而對(duì)于多線程的開發(fā),從JavaEE上表現(xiàn)的并不是特別多,但是在Android開發(fā)之中使用較多,并且需要提醒的是,鄙視面試的過(guò)程之中,多線程所問道的問題是最多的。
1.1 多線程的基本概念
如果要想解釋多線程,那么首先應(yīng)該從單線程開始講起,最早的DOS系統(tǒng)有一個(gè)最大的特征:一旦電腦出現(xiàn)了病毒,電腦會(huì)立刻死機(jī),因?yàn)閭鹘y(tǒng)DOS系統(tǒng)屬于單進(jìn)程的處理方式,即:在同一個(gè)時(shí)間段上只能有一個(gè)程序執(zhí)行,后來(lái)到了windows時(shí)代,電腦即使(非致命)存在了病毒,那么也可以正常使用,只是滿了一些而已,因?yàn)閣indows屬于多進(jìn)程的處理操作,但是這個(gè)時(shí)候的資源依然只有一塊,所以在同一時(shí)間段上會(huì)有多個(gè)程序共同執(zhí)行,而在一個(gè)時(shí)間點(diǎn)上只能有一個(gè)程序在執(zhí)行,多線程實(shí)在一個(gè)進(jìn)程基礎(chǔ)之上的進(jìn)一步劃分,因?yàn)檫M(jìn)程的啟動(dòng)所消耗的時(shí)間是非常長(zhǎng)的,所以在進(jìn)程之上的進(jìn)一步劃分就變得非常重要,而且性能也會(huì)有所提高。
所有的線程一定要依附于進(jìn)程才能夠存在,那么進(jìn)程一旦消失了,線程也一定會(huì)消失,但反過(guò)來(lái)不一定,而Java是為數(shù)不多的支持多線程的開發(fā)語(yǔ)言之一。
1.2 多線程的實(shí)現(xiàn)
在Java之中,如果要想實(shí)現(xiàn)多線程的程序,就必須依靠一個(gè)線程的主體類(叫好比主類的概念一樣,表示的是一個(gè)線程的主類),但是這個(gè)線程的主體類在定義的時(shí)候也需要有一些特殊的要求,這個(gè)類可以繼承Thread類或?qū)崿F(xiàn)Runnable接口來(lái)完成定義。
1.3 繼承Thread類實(shí)現(xiàn)多線程
Java.lang.Thread是一個(gè)線程操作的核心類負(fù)責(zé)線程操作的類,任何類只需要繼承了Thread類就可以成為一個(gè)線程的主類,但是既然是主類必須有它的使用方法,而線程啟動(dòng)的主方法是需要覆寫Thread類中的run()方法才可以(相當(dāng)于線程的主方法)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.day12.demo; class MyThread extends Thread{ private String title; public MyThread(String title){ this .title = title; } public void run(){ for ( int i = 0 ; i < 5 ; i++) { System.out.println( this .title + ",i = " + i); } } } public class ThreadDemo { @SuppressWarnings ( "unused" ) public static void main(String[] args) { MyThread thread1 = new MyThread( "線程1" ); MyThread thread2 = new MyThread( "線程2" ); MyThread thread3 = new MyThread( "線程3" ); thread1.run(); thread2.run(); thread3.run(); } } |
我們只是做了一個(gè)順序打印操作,而和多線程沒有關(guān)系。多線程的執(zhí)行和進(jìn)程是相似的,而是多個(gè)程序交替執(zhí)行,而不是說(shuō)各自執(zhí)行各自的。正確啟動(dòng)多線程的方式應(yīng)該是調(diào)用Thread類中的start()方法。
啟動(dòng)多線程只有一個(gè)方法:public void start(); 調(diào)用此方法會(huì)調(diào)用run()
正確啟動(dòng)多線程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.day12.demo; class MyThread extends Thread{ private String title; public MyThread(String title){ this .title = title; } public void run(){ for ( int i = 0 ; i < 5 ; i++) { System.out.println( this .title + ",i = " + i); } } } public class ThreadDemo { @SuppressWarnings ( "unused" ) public static void main(String[] args) { MyThread thread1 = new MyThread( "線程1" ); MyThread thread2 = new MyThread( "線程2" ); MyThread thread3 = new MyThread( "線程3" ); thread1.start(); thread2.start(); thread3.start(); } } |
此時(shí)再次執(zhí)行代碼發(fā)現(xiàn)所有所有的線程對(duì)象變?yōu)榻惶鎴?zhí)行。所以得出結(jié)論:要想啟動(dòng)線程必須依靠Thread類的start()方法執(zhí)行,線程啟動(dòng)之后會(huì)默認(rèn)調(diào)用了run()方法。
問題:為什么線程啟動(dòng)的時(shí)候必須調(diào)用start()而不是直接調(diào)用run()?
如果想要了解必須打開Java源代碼進(jìn)行瀏覽(在JDK按照目錄下)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0 ) //這個(gè)異常的產(chǎn)生只有在你重復(fù)啟動(dòng)線程的時(shí)候才會(huì)發(fā)生 throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { //只聲明未實(shí)現(xiàn)的方法,同時(shí)使用native關(guān)鍵字定義,native調(diào)用本機(jī)的原生系統(tǒng)函數(shù) start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } |
多線程的實(shí)現(xiàn)一定需要操作系統(tǒng)的支持,那么異常的start0()方法實(shí)際上就和抽象方法很類似沒有方法體,而這個(gè)方法體交給JVM去實(shí)現(xiàn),即:在windows下的JVM可能使用A方法實(shí)現(xiàn)了start0(),而在Linux下的JVM可能使用了B方法實(shí)現(xiàn)了start0(),凡是在調(diào)用的時(shí)候并不會(huì)去關(guān)心集體是何方式實(shí)現(xiàn)了start0()方法,只會(huì)關(guān)心最終的操作結(jié)果,交給JVM去匹配了不同的操作系統(tǒng)。
? 所以多線程操作之中,使用start()方法啟動(dòng)多線程的操作是需要進(jìn)行操作系統(tǒng)函數(shù)調(diào)用的。
1.4 Runnable接口實(shí)現(xiàn)多線程
Thread類的核心功能就是進(jìn)行線程的啟動(dòng),但是如果一個(gè)類直接繼承Threa類就會(huì)造成單繼承的局限,在Java中又提供了有另外一種實(shí)現(xiàn)Runable接口。
1
2
3
|
public interface Runnable{ public void run(); } |
分享:如何區(qū)分新老接口?
? 在JDK之中個(gè),由于其發(fā)展的時(shí)間較長(zhǎng),那么會(huì)出現(xiàn)一些新的接口和老的接口,這兩者有一個(gè)最大的明顯特征:所有最早提供的接口方法里面都不加上public,所有的新接口里面都有public。
通過(guò)Runnable接口實(shí)現(xiàn)多線程
1
2
3
4
5
6
7
8
9
10
11
12
|
package com.day12.demo; class MyThread implements Runnable{ private String title; public MyThread(String title){ this .title = title; } public void run(){ for ( int i = 0 ; i < 5 ; i++) { System.out.println( this .title + ",i = " + i); } } } |
這個(gè)時(shí)候和之前的繼承Thread類區(qū)別不大,但是唯一的好處就是避免了單繼承局限,不過(guò)現(xiàn)在問題也就來(lái)了,剛剛解釋過(guò),如果要想啟動(dòng)多線程依靠Thread類的start()方法完成,之前繼承Thread()類的時(shí)候可以將此方法直接繼承過(guò)來(lái)使用,但現(xiàn)在實(shí)現(xiàn)的是Runnable接口,沒有這個(gè)方法可以繼承了,為了解決這個(gè)問題,還是需要依靠Thread類完成,在Thread類中定義一個(gè)構(gòu)造方法:public Thread(Runnable target),接收Runnable接口對(duì)象。
利用Thread類啟動(dòng)
1
2
3
4
5
6
7
8
9
10
11
|
public class ThreadDemo { @SuppressWarnings ( "unused" ) public static void main(String[] args) { MyThread thread1 = new MyThread( "線程1" ); MyThread thread2 = new MyThread( "線程2" ); MyThread thread3 = new MyThread( "線程3" ); new Thread(thread1).start(); new Thread(thread2).start(); new Thread(thread3).start(); } } |
這個(gè)時(shí)候就實(shí)現(xiàn)了多線程的啟動(dòng),而且沒有了單繼承局限。
1.5 Thread類和Runnable接口實(shí)現(xiàn)多線程的區(qū)別
現(xiàn)在Thread類Runnable接口都可以作為同一功能的方式來(lái)實(shí)現(xiàn)多線程,那么這兩者如果從Java的十年開發(fā)而言,肯定使用Ruanable接口,因?yàn)榭梢杂行У谋苊鈫卫^承的局限,那么除了這些之外,這兩種方式是否還有其他聯(lián)系呢?
為了解釋這兩種方式的聯(lián)系,下面可以打開Thread類的定義:
1
|
Public class Thread Object implements Runnable |
發(fā)現(xiàn)Thread類也是Runnable接口的子類,而如果真的是這樣,那么之前程序的結(jié)構(gòu)就變?yōu)榱艘幌滦问健K哉f(shuō)多線程非常類似于代理模式。
這個(gè)時(shí)候表現(xiàn)出來(lái)的代碼模式非常類似于代理設(shè)計(jì)模式,但是它不是嚴(yán)格意義上的代理設(shè)計(jì)模式,因?yàn)閺膰?yán)格意義上來(lái)講代理設(shè)計(jì)模式之中,代理主體所能夠使用的方法依然是接口中定義的run()方法,而此處代理主題調(diào)用的是start()方法,所以只能夠說(shuō)形式上類似于代理設(shè)計(jì)模式,但本質(zhì)上還是有差別的。
但是除了以上的聯(lián)系之外,對(duì)于Runnable和Thread類還有一個(gè)不太好區(qū)分的區(qū)別:使用Runnable接口可以更加方便的表示出數(shù)據(jù)共享的概念。
買票程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.day12.demo; class MyTicket extends Thread{ private int ticket = 10 ; public void run(){ for ( int i = 0 ; i < 20 ; i++) { if (ticket > 0 ) System.out.println( "買票 =" + this .ticket--); } } } public class TicketDemo { public static void main(String[] args) { new MyTicket().start(); new MyTicket().start(); new MyTicket().start(); } } |
運(yùn)行后發(fā)現(xiàn),數(shù)據(jù)沒有共享。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.day12.demo; class MyTicket extends Thread{ private int ticket = 10 ; public void run(){ for ( int i = 0 ; i < 20 ; i++) { if (ticket > 0 ) System.out.println( "買票 =" + this .ticket--); } } } public class TicketDemo { public static void main(String[] args) { MyTicket mt = new MyTicket(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); } } |
經(jīng)過(guò)改進(jìn)之后,發(fā)現(xiàn)數(shù)據(jù)進(jìn)行共享,但是對(duì)于邏輯是解釋是不好理解的,MyTicket類繼承了Thread類,自己擁有了start()方法但是不執(zhí)行自己的start()方法,而是通過(guò)匿名方法共用MyTicket()實(shí)例化對(duì)象mt調(diào)用匿名方法的start()方法。
再次經(jīng)過(guò)改進(jìn)之后
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.day12.demo; class MyTicket implements Runnable{ private int ticket = 10 ; public void run(){ for ( int i = 0 ; i < 20 ; i++) { if (ticket > 0 ) System.out.println( "買票 =" + this .ticket--); } } } public class TicketDemo { public static void main(String[] args) { MyTicket mt = new MyTicket(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); } } |
通過(guò)MyTicket類實(shí)現(xiàn)Runnable接口來(lái)進(jìn)行改進(jìn),原因是因?yàn)镽unnable接口里面只有一個(gè)自己的run()方法,而此處的start()的方法,是通過(guò)匿名類進(jìn)行調(diào)用start()方法來(lái)實(shí)現(xiàn)線程的啟動(dòng)。
面試題:請(qǐng)解釋多線程的兩種實(shí)現(xiàn)方式區(qū)別?分別編寫程序驗(yàn)證兩種實(shí)現(xiàn)。
多線程的兩種實(shí)現(xiàn)方式都需要一個(gè)線程的主類,而這個(gè)類可以實(shí)現(xiàn)Runnable接口或繼承Thread,不管使用何種方式都必須在子類之中覆寫run()方法,此方法為線程的主方法;
Thread類是Runnable接口的子類,而且使用Runnable接口可以避免單繼承局限,以及更加方便的實(shí)現(xiàn)數(shù)據(jù)共享的概念。
Runnable 接口:
1
2
3
4
5
6
7
8
9
10
11
12
|
class MyThread implements Runnable{ private int ticket= 5 ; public void run(){ for ( int x= 0 ;x< 50 ;x++) if ( this .ticket> 0 ){ System.out.println( this .ticket--); } } } MyThread mt = new MyThread(); new Thread(mt).start(); |
Thread 類:
1
2
3
4
5
6
7
8
9
10
11
12
|
class MyThread extends Thread{ private int ticket= 5 ; public void run(){ for ( int x= 0 ;x< 50 ;x++) if ( this .ticket> 0 ){ System.out.println( this .ticket--); } } } MyThread mt = new MyThread(); mt.start(); |
1.6 線程的操作狀態(tài)
當(dāng)我們多線程調(diào)用start方法之后不會(huì)立刻執(zhí)行,而是進(jìn)入就緒狀態(tài),等待進(jìn)行調(diào)度后執(zhí)行,需要將資源分配給你運(yùn)行后,才可以執(zhí)行多線程的代碼run()中的代碼當(dāng)執(zhí)行一段時(shí)間之后,你需要讓出資源,讓其他線程來(lái)執(zhí)行,這個(gè)時(shí)候run()方法可能還沒有執(zhí)行完成,只執(zhí)行了一半,那么我么我們就需要讓資源,隨后重新進(jìn)入就緒狀態(tài),重新等待分配新資源繼續(xù)執(zhí)行。當(dāng)線程執(zhí)行完畢后才會(huì)進(jìn)入終止?fàn)顟B(tài)。總結(jié)就一句話:線程執(zhí)行需要分配資源,資源不能獨(dú)占,執(zhí)行一會(huì)讓出資源給其他程序執(zhí)行。
1.7 Callable實(shí)現(xiàn)多線程
jdk增加新的工具類java.util.concurrent
1
2
|
@FunctionalInterface public interface Callable<V> |
Runnable中的run()方法雖然也是線程的主方法,但是其沒有返回值,因?yàn)樗脑O(shè)計(jì)遵循了我們主方法的設(shè)計(jì)原則:線程開始就別回頭。但是在很多時(shí)候需要一些返回值,例如:當(dāng)某些線程執(zhí)行完成后可能帶來(lái)一些返回結(jié)果,這種情況下我們就只能通過(guò)Callabale來(lái)實(shí)現(xiàn)多線程。
通過(guò)分析源代碼可以找到一些關(guān)系
Callable定義線程主方法啟動(dòng)并取得多線程執(zhí)行的總結(jié)果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package com.day12.demo; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; class MyTicket1 implements Callable<String>{ @Override public String call() throws Exception { // TODO Auto-generated method stub for ( int i = 0 ; i < 20 ; i++) { System.out.println( "買票 ,x = " + i); } return "票賣完了,下次吧" ; } } public class CallableDemo { @SuppressWarnings ({ "unused" , "rawtypes" , "unchecked" }) public static void main(String[] args) throws Exception { FutureTask<String> task = new FutureTask<>( new MyTicket1()); new Thread(task).start(); System.out.println(task.get()); } } |
這種形式主要就是返回我們的操作結(jié)果。
1.8 線程命名和取得
線程本身是屬于不可見的運(yùn)行狀態(tài)的,即:每次操作的時(shí)候是無(wú)法預(yù)料的,所以如果要想在程序之中操作線程,唯一依靠的就是線程的名稱,而要想取得和設(shè)置線程的名稱可以使用以下的方法:
方法名稱 | 類型 | 描述 |
public Thread(Runnable target,String name); | 構(gòu)造 | 聲明參數(shù) |
public final void setName(String name); | 普通 | 設(shè)置線程名稱 |
public final String getName() | 普通 | 取得線程名稱 |
但是由于線程的狀態(tài)不確定,所以每次可以操作的線程都是正在執(zhí)行run()方法的線程,那么取得當(dāng)前線程對(duì)象的方法:public static Thread currentThread()。
線程名稱的取得
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.day12.demo; class MyThread implements Runnable{ public void run(){ System.out.println(Thread.currentThread().getName()); } } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub MyThread mt = new MyThread(); new Thread(mt).start(); //Thread-0 new Thread(mt).start(); //Thread-1 new Thread(mt).start(); //Thread-2 new Thread(mt, "A" ).start(); //A new Thread(mt, "B" ).start(); //B new Thread(mt, "C" ).start(); //C } } |
如果說(shuō)現(xiàn)在為線程設(shè)置名字的話,那么會(huì)使用用戶定義的名字,而如果沒有設(shè)置線程名稱,會(huì)自動(dòng)分配一個(gè)名稱這一點(diǎn)操作和之前講解的static命名類似。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.day12.demo; class MyThread2 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName()); } } public class RenameThreadDemo { public static void main(String[] args) { MyThread2 mt = new MyThread2(); mt.run(); //直接通過(guò)對(duì)象調(diào)用方法 new Thread(mt).start(); } } |
觀察以上程序我們發(fā)現(xiàn),線程的啟動(dòng)都是通過(guò)主線程創(chuàng)建并啟動(dòng)的,主方法就是一個(gè)線程。
進(jìn)程在哪里?
實(shí)際上每當(dāng)使用了java命令去解釋程序的時(shí)候,都表示啟動(dòng)了一個(gè)新的JVM進(jìn)程。而主方法只是這個(gè)進(jìn)程上的一個(gè)線程而已。
1.9 線程的休眠
線程的休眠指的是讓程序休息一會(huì)等時(shí)間到了在進(jìn)行執(zhí)行。方法:public static void sleep(long millis) throws InterruptedException,設(shè)置的休眠單位是毫秒。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package com.day12.demo; class MyThread implements Runnable{ public void run(){ for ( int x= 0 ;x< 100 ;x++){ try { Thread.sleep( 100 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "x=" +x); } } } public class Test { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub MyThread mt = new MyThread(); new Thread(mt, "線程A" ).start(); new Thread(mt, "線程B" ).start(); } } |
1.10 線程的優(yōu)先級(jí)
從理論上講,線程的優(yōu)先級(jí)越高,越有可能先執(zhí)行。如果要想操作線程的優(yōu)先級(jí)有如下兩個(gè)方法:
設(shè)置線程優(yōu)先級(jí):public final void setPriority(int newPriority);
取得線程優(yōu)先級(jí):public final int getPriority();
發(fā)現(xiàn)設(shè)置取得優(yōu)先級(jí)的時(shí)候都是利用一個(gè)int型數(shù)據(jù)的操作,而這個(gè)int型數(shù)據(jù)有三種取值:
? **最高優(yōu)先級(jí):**public static final int MAX_PRIORITY,10;
? **中等優(yōu)先級(jí):**public static final int NORM_PRIORITY,5;
? **最低優(yōu)先級(jí):**public static final int MIN_PRIORITY,1;
設(shè)置優(yōu)先級(jí)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package com.day12.demo; class MyThread3 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for ( int i = 0 ; i < 10 ; i++) { System.out.println(Thread.currentThread().getName() + "i = " + i); } } } public class PriorityDemo { public static void main(String[] args) { MyThread3 mt = new MyThread3(); Thread thread1 = new Thread(mt, "線程A" ); Thread thread2 = new Thread(mt, "線程B" ); Thread thread3 = new Thread(mt, "線程C" ); thread1.setPriority(Thread.MIN_PRIORITY); thread2.setPriority(Thread.MAX_PRIORITY); thread1.start(); thread2.start(); thread3.start(); } } |
主方法只是一個(gè)中等優(yōu)先級(jí)。
1.11 線程的同步與死鎖
所謂的同步問題是指多個(gè)線程操作統(tǒng)一次元所帶來(lái)的信息安全性問題,
下面模擬一個(gè)簡(jiǎn)單的賣票程序,要求有3個(gè)線程,賣10張票。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package com.day12.demo; class MyTicket implements Runnable{ private int ticket = 10 ; public void run(){ for ( int i = 0 ; i < 20 ; i++) { if (ticket > 0 ){ try { Thread.sleep( 200 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "買票 =" + this .ticket--); } } } } public class TicketDemo { public static void main(String[] args) { MyTicket mt = new MyTicket(); new Thread(mt, "票販子A" ).start(); new Thread(mt, "票販子B" ).start(); new Thread(mt, "票販子C" ).start(); } } |
運(yùn)行上面程序發(fā)現(xiàn),票數(shù)為0或者為負(fù)數(shù),這種操作我們稱為不同步操作。
不同步的唯一好處就是處理速度快(多個(gè)線程并發(fā)執(zhí)行),而去銀行是一個(gè)業(yè)務(wù)員對(duì)應(yīng)一個(gè)客戶,這個(gè)速度必然很慢。數(shù)據(jù)的不同步對(duì)于訪問是不安全的操作。
同步是指所有的線程不是一起進(jìn)入方法中執(zhí)行,而是一個(gè)一個(gè)進(jìn)來(lái)執(zhí)行。
如果要寫實(shí)現(xiàn)這把鎖的功能,那么可以使用synchronized關(guān)鍵字進(jìn)行處理,有兩種處理模式:同步代碼塊、同步方法。
同步代碼塊
如果要使用這種情況必須設(shè)置一個(gè)要鎖定當(dāng)前對(duì)象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.day12.demo; class MyTicket implements Runnable{ private int ticket = 2000 ; public void run(){ for ( int i = 0 ; i < 1000 ; i++) { //在同一時(shí)刻,只允許一個(gè)線程進(jìn)入并且操作,其他線程需要等待 synchronized ( this ){ //線程的邏輯鎖 if (ticket > 0 ){ try { Thread.sleep( 10 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "買票 =" + this .ticket--); } } } } } public class TicketDemo { public static void main(String[] args) { MyTicket mt = new MyTicket(); Thread thread1 = new Thread(mt, "票販子A" ); thread1.setPriority(Thread.MIN_PRIORITY); thread1.start(); new Thread(mt, "票販子B" ).start(); new Thread(mt, "票販子C" ).start(); } } |
同步方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package com.day12.demo; class MyTicket implements Runnable{ private int ticket = 2000 ; public void run(){ for ( int i = 0 ; i < 1000 ; i++) { //在同一時(shí)刻,只允許一個(gè)線程進(jìn)入并且操作,其他線程需要等待 synchronized ( this ){ //線程的邏輯鎖 this .sale(); } } } public synchronized void sale(){ if (ticket > 0 ){ try { Thread.sleep( 10 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "買票 =" + this .ticket--); } } } public class TicketDemo { public static void main(String[] args) { MyTicket mt = new MyTicket(); Thread thread1 = new Thread(mt, "票販子A" ); thread1.setPriority(Thread.MIN_PRIORITY); thread1.start(); new Thread(mt, "票販子B" ).start(); new Thread(mt, "票販子C" ).start(); } } |
同步雖然可以保證數(shù)據(jù)的完整性(線程安全操作),但是其執(zhí)行的速度很慢。
1.12 死鎖
一個(gè)線程執(zhí)行完畢后才可以繼續(xù)執(zhí)行,但是如果現(xiàn)在相關(guān)的幾個(gè)線程,彼此幾個(gè)線程都在等待(同步),那么就會(huì)造成死鎖。
模擬死鎖程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package com.day12.demo; class JieFei{ public synchronized void say(Person Person){ System.out.println( "給錢放人" ); Person.get(); } public synchronized void get(){ System.out.println( "得到錢" ); } } class Person{ public synchronized void say(JieFei jiefei){ System.out.println( "放人就給錢" ); jiefei.get(); } public synchronized void get(){ System.out.println( "得到人" ); } } public class DeadLock implements Runnable { JieFei jie = new JieFei(); Person person = new Person(); public static void main(String[] args) { // TODO 自動(dòng)生成的方法存根 new DeadLock(); } public DeadLock(){ new Thread( this ).start(); jie.say(person); } @Override public void run() { // TODO 自動(dòng)生成的方法存根 person.say(jie); } } |
死鎖實(shí)在日后多線程程序開發(fā)之中經(jīng)常會(huì)遇見問題,而以上的代碼并沒有任何實(shí)際意義,大概可以理解死鎖的操作形式就可以了,不用去研究程序。記住一句話:數(shù)據(jù)要想完整操作必須使用同步,但是過(guò)多的同步會(huì)造成死鎖。
面試題:請(qǐng)問多線程操作統(tǒng)一資源的時(shí)候要考慮到那些,會(huì)帶來(lái)的問題?
多線程訪問統(tǒng)一資源的時(shí)候一定要考慮同步的問題,但是過(guò)多的同步會(huì)帶來(lái)死鎖。
綜合案例
生產(chǎn)者和消費(fèi)者是一道最為經(jīng)典的供求案例:provider、consumer。不管是之后的分布式開發(fā)還是其他開發(fā)都被大量采用。
生產(chǎn)者只是負(fù)責(zé)生產(chǎn)數(shù)據(jù),而生產(chǎn)者每生產(chǎn)一個(gè)完整的數(shù)據(jù),消費(fèi)者就把這個(gè)數(shù)據(jù)拿走。假設(shè)生產(chǎn)如下數(shù)據(jù) src="/uploads/allimg/211130/11495J426-11.jpg" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package com.day12.demo; class Message{ private String title; private String note; public String getTitle() { return title; } public void setTitle(String title) { this .title = title; } public String getNote() { return note; } public void setNote(String note) { this .note = note; } } class Productor implements Runnable{ Message msg = null ; public Productor(Message msg){ this .msg=msg; } @Override public void run() { // TODO 自動(dòng)生成的方法存根 for ( int x = 0 ;x< 50 ;x++){ if (x% 2 == 0 ){ try { msg.setTitle( "生產(chǎn)" ); Thread.sleep( 100 ); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } msg.setNote( "出庫(kù)" ); } else { msg.setNote( "拿貨" ); try { Thread.sleep( 100 ); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } msg.setNote( "消費(fèi)" ); } } } } class Consumer implements Runnable{ Message msg = null ; public Consumer(Message msg){ this .msg=msg; } @Override public void run() { // TODO 自動(dòng)生成的方法存根 for ( int x= 0 ;x< 50 ;x++){ try { Thread.sleep( 100 ); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } System.out.println( this .msg.getTitle()+ "--->" + this .msg.getNote()); } } } public class PCDemo { public static void main(String args[]){ // TODO 自動(dòng)生成的方法存根 Message msg = new Message(); Productor pro = new Productor(msg); Consumer con = new Consumer(msg); new Thread(pro).start(); new Thread(con).start(); } } |
但是異常的代碼模型出現(xiàn)了如下的兩個(gè)嚴(yán)重的問題:
數(shù)據(jù)錯(cuò)位了出現(xiàn)了重復(fù)取出和重復(fù)設(shè)置的問題
1.解決數(shù)據(jù)錯(cuò)位問題:依靠同步解決
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
package com.day12.demo; class Message { private String title; private String note; public synchronized void set(String title, String note) { try { Thread.sleep(50); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } this.title = title; try { Thread.sleep(100); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } this.note = note; } public synchronized void get() { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } System.out.println(this.title + "--->" + this.note); } } class Productor implements Runnable { Message msg; public Productor(Message msg) { this.msg = msg; } @Override public void run() { // TODO 自動(dòng)生成的方法存根 for (int x = 0; x < 50; x++) { if (x % 2 == 0) { msg.set("生產(chǎn)", "出庫(kù)"); } else { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } msg.set("拿貨", "消費(fèi)"); } } } } class Consumer implements Runnable { Message msg = null; public Consumer(Message msg) { this.msg = msg; } @Override public void run() { // TODO 自動(dòng)生成的方法存根 for (int x = 0; x < 50; x++) { msg.get(); } } } public class PCDemo { public static void main(String args[]) { // TODO 自動(dòng)生成的方法存根 Message msg = new Message(); Productor pro = new Productor(msg); Consumer con = new Consumer(msg); new Thread(pro).start(); new Thread(con).start(); } } |
雖然解決了錯(cuò)位的問題,但是重復(fù)設(shè)置重復(fù)取出更加嚴(yán)重了。
2.解決數(shù)據(jù)的重復(fù)設(shè)置和重復(fù)取出
要想解決重復(fù)的問題需要等待及喚醒機(jī)制,而這一機(jī)制的實(shí)現(xiàn)只能依靠Object類完成,在Object類之中定義了以下的三個(gè)方法完成線程操作:
方法名稱 | 類型 | 描述 |
public final void wait() throws InterruptedException | 普通 | 等待、死等 |
public final void notify() | 普通 | 喚醒第一個(gè)等待線程 |
public final void notifyAll() | 普通 | 喚醒全部等待線程 |
通過(guò)等待與喚醒機(jī)制來(lái)解決數(shù)據(jù)的重復(fù)操作問題
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
package com.day12.demo; class Message { private String title; private String note; //flag = true 允許生產(chǎn)但是不允許消費(fèi)者取走 //flag = false 生產(chǎn)完畢 允許消費(fèi)者取走,但是不能夠生產(chǎn) private boolean flag = false ; public synchronized void set(String title, String note) { if (flag == true ){ //生產(chǎn)完畢 允許消費(fèi)者取走,但是不能夠生產(chǎn) try { super .wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this .title = title; try { Thread.sleep( 10 ); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } this .note = note; flag = true ; super .notify(); } public synchronized void get() { if (flag == false ){ //允許生產(chǎn)但是不允許消費(fèi)者取走 try { super .wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { Thread.sleep( 50 ); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } System.out.println( this .title + "--->" + this .note); flag = false ; super .notify(); } } class Productor implements Runnable { Message msg; public Productor(Message msg) { this .msg = msg; } @Override public void run() { // TODO 自動(dòng)生成的方法存根 for ( int x = 0 ; x < 50 ; x++) { if (x % 2 == 0 ) { msg.set( "生產(chǎn)" , "出庫(kù)" ); } else { try { Thread.sleep( 100 ); } catch (InterruptedException e) { // TODO 自動(dòng)生成的 catch 塊 e.printStackTrace(); } msg.set( "拿貨" , "消費(fèi)" ); } } } } class Consumer implements Runnable { Message msg = null ; public Consumer(Message msg) { this .msg = msg; } @Override public void run() { // TODO 自動(dòng)生成的方法存根 for ( int x = 0 ; x < 50 ; x++) { msg.get(); } } } public class PCDemo { public static void main(String args[]) { // TODO 自動(dòng)生成的方法存根 Message msg = new Message(); Productor pro = new Productor(msg); Consumer con = new Consumer(msg); new Thread(pro).start(); new Thread(con).start(); } } |
面試題:請(qǐng)解釋sleep()和wait()的區(qū)別?
- sleep()是Thread類中定義的方法,到了一定的時(shí)間后該休眠的線程自動(dòng)喚醒,自動(dòng)喚醒。
- wait()是Object類中定義的方法,如果要想喚醒,必須使用notify()、notifyAll()才能喚醒,手動(dòng)喚醒。
到此這篇關(guān)于Day12基礎(chǔ)不牢地動(dòng)山搖-Java基礎(chǔ)的文章就介紹到這了,更多相關(guān)Java基礎(chǔ)內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/zsr6135/article/details/119740967