Java多執行緒核心技術(一):基礎知識總結
概念
程序:程序是作業系統結構的基礎,是一次程式的執行,是一個程式及其資料在處理機上順序執行時所發生的活動,是程式在一個程式集合上執行的過程,它是系統進行資源分配和排程的一個基本單位。
執行緒:執行緒是程序中獨立執行的子任務。使用多執行緒技術後,可以在同一時間執行更多不同種類的任務。
使用多執行緒
第一種方式:繼承Thread類,並實現run方法
第二種方式:實現Runnable介面
注意:1、程式碼的執行結果與程式碼的順序無關:執行緒是一個子任務,CPU以不確定的方式,或者說以隨機的時間來呼叫執行緒中的run方法。
2、Thread.java類中的start()方法通知"執行緒規劃器"此執行緒已經準備就緒,等待呼叫執行緒物件的run()方法。這個過程其實就是讓系統安排一個時間來呼叫Thread中的run()方法,也就是使執行緒得到執行,啟動執行緒,具有非同步執行的效果,所以如果在程式中直接呼叫執行緒的run方法,那程式就是順序執行的。
Thread類的結構:public class Thread implements Runnable
在Thread類的8個建構函式中,有兩個建構函式Thread(Runnable target)和Thread(Runnable target,String name)可以傳遞Runnable介面,說明建構函式支援傳入一個Runnable介面的物件。而Thread類實現了Runnable介面,所以完全可以將一個Thread物件作為Thread建構函式的引數傳入,這樣該Thread物件實現的run()方法就交由其他的執行緒進行呼叫。
共享資料
實現5個執行緒共同對一個count變數進行減法操作:
執行結果如下:class MyThread extends Thread{ public int count = 5; @Override public void run(){ super.run(); count--; System.out.println("由 " + this.currentThread().getName() + "計算,count="+count); } } public class TestClass{ public static void main(String[] args){ MyThread mythread = new MyThread(); Thread a = new Thread(mythread,"A"); Thread b = new Thread(mythread,"B"); Thread c = new Thread(mythread,"C"); Thread d = new Thread(mythread,"D"); Thread e = new Thread(mythread,"E"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
在JVM中,i--的操作分成如下3步:
(1)取得原有i值,
(2)計算i-1,
(3)對i進行賦值。
當五個執行緒同時進行操作i--時,其中的某個或某些執行緒在沒執行完這三個步驟的情況下,其他的執行緒就插入進來了,就會造成結果的混亂。解決這個問題的方法是在潤方法錢加synchronized關鍵字,保證run方法的原子性操作。synchronized可以在任意物件及方法上加鎖,而加鎖的這段程式碼稱為”互斥區“或者”臨界區“,當一個執行緒想執行同步方法裡面的程式碼時,執行緒首先嚐試去拿這把鎖,如果能夠拿到這把鎖,那麼這個執行緒就可以執行synchronized裡面的程式碼。如果不能拿到這把鎖,那麼這個執行緒就會不斷地嘗試拿這把鎖,直到能夠拿到為止,而且是有多個執行緒同時去爭搶這把鎖。
currentThread()方法
currentThread()方法可返回程式碼段正在被哪個執行緒呼叫的資訊。
當直接呼叫thread的run方法時,則run方法不是有其所在的執行緒去呼叫,而是由主執行緒去呼叫。
class MyThread extends Thread{
public MyThread(){
System.out.println("建構函式開始");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("this.Name=" + this.getName());
System.out.println("建構函式結束");
}
@Override
public void run(){
System.out.println("run方法開始");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("this.Name=" + this.getName());
System.out.println("run方法結束");
}
}
public class TestClass{
public static void main(String[] args){
MyThread mythread = new MyThread();
Thread t = new Thread(mythread);
t.setName("A");
t.start();
}
}
輸出結果為:
建構函式開始
Thread.currentThread().getName()=main
this.Name=Thread-0
建構函式結束
run方法開始
Thread.currentThread().getName()=A
this.Name=Thread-0
run方法結束
在呼叫MyThread建構函式的執行緒是Main執行緒,而呼叫mythread的run方法的是名稱為A的執行緒。
isAlive()方法
isAlive()方法的功能是判斷當前執行緒是否處於活動狀態,活動狀態就是執行緒已經啟動且尚未終止。執行緒處於正在執行或準備開始執行的狀態,就認為執行緒是“存活”的。
class MyThread extends Thread{
public MyThread(){
System.out.println("建構函式開始");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive());
System.out.println("this.Name=" + this.getName());
System.out.println("this.isAlive()" + this.isAlive());
System.out.println("建構函式結束");
}
@Override
public void run(){
System.out.println("run方法開始");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive());
System.out.println("this.Name=" + this.getName());
System.out.println("this.isAlive()" + this.isAlive());
System.out.println("run方法結束");
}
}
public class TestClass{
public static void main(String[] args){
MyThread mythread = new MyThread();
Thread t = new Thread(mythread);
t.setName("A");
t.start();
}
}
程式執行結果如下:
建構函式開始
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()=true
this.Name=Thread-0
this.isAlive()false
建構函式結束
run方法開始
Thread.currentThread().getName()=A
Thread.currentThread().isAlive()=true
this.Name=Thread-0
this.isAlive()false
run方法結束
這說明MyThread在建構函式中並沒有存活,由於把MyThread的run方法交給了其他執行緒執行,所以在run方法中MyThread也不是存活的。
sleep()方法
sleep()方法的作用是在指定的毫秒數內讓當前“正在執行的執行緒”休眠(暫停執行)。這個“正在執行的執行緒”是指this.currentThread()返回的執行緒。
class MyThread extends Thread{
@Override
public void run(){
try {
System.out.println("run threadName=" + this.currentThread().getName()+" begin="+System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("run threadName=" + this.currentThread().getName()+" end ="+System.currentTimeMillis());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TestClass{
public static void main(String[] args){
MyThread mythread = new MyThread();
System.out.println("begin="+System.currentTimeMillis());
mythread.start();
System.out.println("end ="+System.currentTimeMillis());
}
}
程式執行結果如下:
begin=1487766083887
end =1487766083887
run threadName=Thread-0 begin=1487766083887
run threadName=Thread-0 end =1487766085888
由於main執行緒與Mythread2執行緒是非同步執行的,所以首先列印的資訊為begin和end。而MyThread2執行緒是隨後執行的,在最後兩行列印run begin和run end相關的資訊。
getId()方法
getId()方法的作用是取的執行緒的唯一標識
停止執行緒
在Java中有以下3種方法可以終止正在執行的執行緒:
(1)使用退出標誌,使執行緒正常退出,也就是當run方法完成後執行緒終止。
(2)使用stop方法強行終止執行緒,但是不推薦使用這種方法,因為stop方法和suspend及resume方法一樣,都是作廢過期的方法,使用它們可能會產生不可預料的結果。
如果使用stop方法強制讓執行緒停止則有可能會使一下清理性的工作得不到完成。另一個情況就是對鎖定的物件進行了“解鎖”,導致資料得不到同步的處理,出現數據不一致的問題。
(3)使用interrupt方法中斷執行緒,呼叫interrupt()方法僅僅是在當前執行緒中打了一個停止的標記,並不是真的停止執行緒。
判斷執行緒是否是停止狀態:
(1)this.interrupted():測試當前的執行緒是否已經中斷,靜態方法。執行緒的中斷狀態由該方法清除。所以,連續兩次呼叫該方法,則第二次呼叫返回false(在第一次呼叫已經 清除了其中斷狀態之後,第二次呼叫檢驗完中斷狀態前,當前執行緒再次中斷的情況除外)。
(2)this.isInterrupted():測試當前執行緒是否已經中斷,非靜態方法,並不會清除狀態標誌。
public class TestClass{
public static void main(String[] args){
try {
MyThread mythread = new MyThread();
mythread.start();
Thread.sleep(1000);
mythread.interrupt();
System.out.println("當前執行緒是否停止? = "+Thread.interrupted());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
程式執行輸出當前執行緒是否停止? = false
這是因為mythread執行緒終止了,但是main執行緒一直在執行,這個“當前執行緒”就是main,所以列印了false。
在沉睡中停止
如果線上程的sleep()狀態下停止執行緒,會丟擲java.lang.InterruptedException異常,並且清除停止狀態值,使之變成false。先中斷執行緒在呼叫sleep()方法,結果是一樣的。
暫停執行緒
暫停執行緒意味著此執行緒還可以恢復執行。在Java多執行緒中,可以使用suspend()方法暫停執行緒,使用resume()方法恢復執行緒的執行。
在suspend與resume方法時,如果使用不當,極易造成公共的同步物件的獨佔,是的其他執行緒無法訪問公共同步物件。
class MyThread extends Thread{
private long i = 0;
@Override
public void run(){
while(true){
i++;
}
}
}
public class TestClass{
public static void main(String[] args){
try {
MyThread mythread = new MyThread();
mythread.start();
Thread.sleep(1000);
mythread.suspend();
System.out.println("main end!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
程式會打印出main end,但是將MyThread改為如下的寫法,執行程式,控制檯將不列印main end,這是因為當程式執行到println()方法內部停止時,同步鎖未被釋放。方法println()原始碼如下所示:
public void println(long x){
synchronized(this){
print(x);
newLine();
}
}
yield方法
yield方法的作用是放棄當前的CPU資源,將它讓給其他的任務去佔用CPU執行時間。但放棄的時間不確定,有可能剛剛放棄,馬上又獲得CPU時間片。
class MyThread extends Thread{
@Override
public void run(){
long beginTime = System.currentTimeMillis();
int count = 0;
for(int i = 0; i < 50000000; i++){
//Thread.yield();
count += i;
}
long endTime = System.currentTimeMillis();
System.out.println("用時:"+(endTime - beginTime) + "毫秒!");
}
}
public class TestClass{
public static void main(String[] args){
MyThread thread = new MyThread();
thread.start();
}
}
正常情況下執行時間用了3毫秒,把//Thread.yield()的註釋去掉,用時3189毫秒!
執行緒的優先順序
優先順序較高的執行緒得到的CPU資源較多,也就是CPU優先執行優先順序較高的執行緒物件中的任務。設定執行緒的優先順序使用setPriority(int newPriority)方法。在Java中,執行緒的優先順序分為1~10這10個等級,如果小於1或大於10,則JDK丟擲異常throw new IllegalArgumentException()。
JDK中使用3個常量來預置定義優先順序的值,程式碼如下:
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
在Java中,執行緒的優先順序具有繼承性,比如A執行緒啟動B執行緒,則B執行緒的優先順序與A是一樣的。下面是程式碼實現的例子:
class MyThread1 extends Thread{
@Override
public void run(){
System.out.println("MyThread1 run priority="+this.getPriority());
MyThread2 thread2 = new MyThread2();
thread2.start();
}
}
class MyThread2 extends Thread{
@Override
public void run(){
System.out.println("MyThread2 run priority="+this.getPriority());
}
}
public class TestClass{
public static void main(String[] args){
System.out.println("main thread begin priority="+Thread.currentThread().getPriority());
Thread.currentThread().setPriority(6);
System.out.println("main thread begin priority="+Thread.currentThread().getPriority());
MyThread1 thread1 = new MyThread1();
thread1.start();
}
}
程式執行結果為:
main thread begin priority=5
main thread begin priority=6
MyThread1 run priority=6
MyThread2 run priority=6
守護執行緒
在Java執行緒中有兩種執行緒,一種是使用者執行緒,另一種是守護執行緒。
守護執行緒是一種特殊的執行緒,它的特性有“陪伴”的含義,當程序中不存在非守護執行緒了,則守護執行緒自動銷燬。典型的守護執行緒就是垃圾回收執行緒,當程序中沒有非守護執行緒了,則垃圾回收執行緒也就沒有存在的必要了,自動銷燬。
class MyThread extends Thread{
private int i = 0;
@Override
public void run(){
try {
while(true){
i++;
System.out.println("i="+i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TestClass{
public static void main(String[] args){
try {
MyThread thread = new MyThread();
thread.setDaemon(true);
thread.start();
Thread.sleep(5000);
System.out.println("我離開thread物件也不再列印了,也就是停止了!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如下是執行結果,當main執行緒執行完,守護執行緒MyThread就銷燬了。
i=1
i=2
i=3
i=4
i=5
我離開thread物件也不再列印了,也就是停止了!