java 線程thread基礎知識點總結

來源:互聯網
上載者:User

1.線程Thread是指程式的運行流程。多線程的機制可以同時運行多個程式塊,使程式啟動並執行效率更高,也解決了傳統程式設計語言所無法解決的問題。

2.如果在類裡面要啟用線程,必須先做好下面兩項準備:
1.此類必須是擴充自Thread類,使自己成為它的子類。
2.線程的處理常式必須編在run()方法內。

3.run()方法是定義在Thread類裡面的一個方法,因此把線程的程式碼編寫在run()方法裡,所做的就是對Thread.run()方法的複寫。

4.Runnable介面裡聲明了抽象的run()方法,因此必須在實現了Runnable介面的類裡明確定義run()方法(必須實現run()方法)。

5.每一個線程,在其建立和消亡之前,均會處於下列五種狀態之一:建立、就緒、運行、阻塞、終止。

6.暫停狀態的線程可由下列的情況所產生:
1.該線程調用對象的wait()方法時;
2.該線程本身調用sleep()方法時;
3.該線程和另一個線程join()在一起時。

7.被凍結因素消失的原因有:
1.如果線程是由調用對象的wait()方法所凍結,則該對象的notify()方法被調用時可解除凍結;
2.線程進入休眠sleep狀態,但指定的休眠時間到了。

8.當線程的run()方法運行結束,或是由線程調用它的stop()方法時,由線程進入消亡狀態。

9.Thread類裡的sleep()方法可以用來控制線程的休眠狀態,休眠的時間要視sleep()裡的參數而定。

10.要強制某一線程運行,可以用join()方法。

11.join()方法會拋出InterruptedException的異常,所以編寫時必須把join()方法編寫在try-catch塊內進行異常的捕獲。

12.當多個線程對象操縱同一共用資源時,要使用synchronized關鍵字來進行資源的同步處理,可以是synchronized(this){要同步的代碼塊} 或者是聲明方法時使用synchronized關鍵字


下面就做個例子:
 
一、標準例子
 
定義了MyThreadLocal類,建立它的一個對象tlt,分別給四個線程使用,結果四個線程tlt變數並沒有出現共用現象,二是各用各的,這說明,四個線程使用的是tlt的副本(複製品)。
 

 代碼如下 複製代碼

/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public class MyThreadLocal {
        //定義了一個ThreadLocal變數,用來儲存int或Integer資料
        private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
                @Override
                protected Integer initialValue() {
                        return 0;
                }
        };

        public Integer getNextNum() {
                //將tl的值擷取後加1,並更新設定t1的值
                tl.set(tl.get() + 1);
                return tl.get();
        }
}
/**
* 測試線程
*
* @author leizhimin 2010-1-5 10:39:18
*/
public class TestThread extends Thread {
        private MyThreadLocal tlt = new MyThreadLocal();

        public TestThread(MyThreadLocal tlt) {
                this.tlt = tlt;
        }

        @Override
        public void run() {
                for (int i = 0; i < 3; i++) {
                        System.out.println(Thread.currentThread().getName() + "t" + tlt.getNextNum());
                }
        }
}
/**
* ThreadLocal測試
*
* @author leizhimin 2010-1-5 10:43:48
*/
public class Test {
        public static void main(String[] args) {
                MyThreadLocal tlt = new MyThreadLocal();
                Thread t1 = new TestThread(tlt);
                Thread t2 = new TestThread(tlt);
                Thread t3 = new TestThread(tlt);
                Thread t4 = new TestThread(tlt);
                t1.start();
                t2.start();
                t3.start();
                t4.start();

        }
}

可以看出,三個線程各自獨立編號,互不影響:

hread-0  1
Thread-1  1
Thread-0  2
Thread-1  2
Thread-0  3
Thread-1  3
Thread-2  1
Thread-3  1
Thread-2  2
Thread-3  2
Thread-2  3
Thread-3  3

Process finished with exit code 0
tlt對象是一個,廢話tl對象也是一個,因為組合關係是一對一的。但是tl對象內部的Map隨著線程的增多,會建立很多Integer對象。只是Integer和int已經通用了。所以感覺不到Integer的對象屬性。
 
二、不用ThreadLocal
 
假如不用ThreadLocal,只需要將MyThreadLocal類重新定義為:

 代碼如下 複製代碼

/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public class MyThreadLocal {
        private Integer t1 = 0;
        public Integer getNextNum(){
                return t1=t1+1;
        }

 

//        //定義了一個ThreadLocal變數,用來儲存int或Integer資料
//        private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
//                @Override
//                protected Integer initialValue() {
//                        return 0;
//                }
//        };
//
//        public Integer getNextNum() {
//                //將tl的值擷取後加1,並更新設定t1的值
//                tl.set(tl.get() + 1);
//                return tl.get();
//        }
}

然後運行測試:
Thread-2  1
Thread-2  2
Thread-1  4
Thread-1  6
Thread-3  3
Thread-3  9
Thread-3  10
Thread-1  8
Thread-0  7
Thread-0  11
Thread-0  12
Thread-2  5

Process finished with exit code 0
從這裡可以看出,四個線程共用了tlt變數,結果每個線程都直接修改tlt的屬性。
 
三、自己實現個ThreadLocal
 

 代碼如下 複製代碼

package com.lavasoft.test2;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public class MyThreadLocal {

        //定義了一個ThreadLocal變數,用來儲存int或Integer資料
        private com.lavasoft.test2.ThreadLocal<Integer> tl = new com.lavasoft.test2.ThreadLocal<Integer>() {
                @Override
                protected Integer initialValue() {
                        return 0;
                }
        };

        public Integer getNextNum() {
                //將tl的值擷取後加1,並更新設定t1的值
                tl.set(tl.get() + 1);
                return tl.get();
        }
}

class ThreadLocal<T> {
        private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>());

        public ThreadLocal() {
        }

        protected T initialValue() {
                return null;
        }

        public T get() {
                Thread t = Thread.currentThread();
                T obj = map.get(t);
                if (obj == null && !map.containsKey(t)) {
                        obj = initialValue();
                        map.put(t, obj);
                }
                return obj;
        }

        public void set(T value) {
                map.put(Thread.currentThread(), value);
        }

        public void remove() {
                map.remove(Thread.currentThread());
        }
}

運行測試:
Thread-0  1
Thread-0  2
Thread-0  3
Thread-2  1
Thread-2  2
Thread-3  1
Thread-2  3
Thread-3  2
Thread-1  1
Thread-3  3
Thread-1  2
Thread-1  3

Process finished with exit code 0
很意外,這個山寨版的ThreadLocal也同樣運行很好,實現了JavaAPI中ThreadLocal的功能。

多線程優點:  

A、進程之間不能共用記憶體,但線程之間共用記憶體非常容易。   
B、系統建立進程需要為該進程重新分配系統資源,但建立線程則代價要小得多,因此使用線程來實現多任務並發比多進程的效率高。   
C、Java語言內建多線程功能支援,而不是單純的作為底層作業系統的調度方式,從而簡化Java的多線程編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.