JAVA多執行緒入門

weixin_34248705發表於2018-05-25

繼承Thread父類

執行緒程式碼執行順序和呼叫順序無關,例如:

public class MyThread extends Thread {

    @Override
    public void run(){
        super.run();
        System.out.println("MyThread");
    }
/**執行順序存疑
 * 並沒有發現隨機性 */
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.run();
        System.out.println("mainThread");

    }
    
}

上述程式碼執行理論上“MyThread”和“mainThread”列印順序是隨機的,和呼叫順序無關,實際情況存疑。

執行緒執行具有隨機性,CPU的執行具有不確定性

public class MyThread1 extends Thread {

    @Override
    public void run(){
        try {
            for (int i = 0;i < 10;i++){
            int time = (int) (Math.random()*1000);
            Thread.sleep(time);
            System.out.println("run:"+Thread.currentThread().getName());
            }
        }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    public static void main(String[] args) throws InterruptedException {
        MyThread1 thread = new MyThread1();
        thread.setName("myThread");
        thread.start();
        for (int i = 0; i<10;i++){
            int time = (int) (Math.random()*1000);
                Thread.sleep(time);
                System.out.println("main:"+Thread.currentThread().getName());
        }

    }
}

/*結果:
run:myThread
run:myThread
run:myThread
main:main
main:main
run:myThread
run:myThread
run:myThread
main:main
main:main
main:main
main:main
run:myThread
run:myThread
main:main
run:myThread
run:myThread
main:main
main:main
main:main
*/

start方法並不代表執行緒啟動,執行緒啟動順序由CPU執行順序決定,無序性。

public class MyThread2 extends Thread {
    private int i;
    public MyThread2(int i){
        super();
        this.i = i;
    }
    @Override
    public void run(){
        System.out.println("myThread:"+i);
    }

    public static void main(String[] args){
        MyThread2 t1 = new MyThread2(1);
        MyThread2 t2 = new MyThread2(2);
        MyThread2 t3 = new MyThread2(3);
        MyThread2 t4 = new MyThread2(4);
        MyThread2 t5 = new MyThread2(5);
        MyThread2 t6 = new MyThread2(6);
        MyThread2 t7 = new MyThread2(7);
        MyThread2 t8 = new MyThread2(8);
        MyThread2 t9 = new MyThread2(9);
        MyThread2 t10 = new MyThread2(10);
        MyThread2 t11 = new MyThread2(11);
        MyThread2 t12 = new MyThread2(12);
        MyThread2 t13 = new MyThread2(13);
        MyThread2 t14 = new MyThread2(14);
        MyThread2 t15 = new MyThread2(15);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();
        t11.start();
        t12.start();
        t13.start();
        t14.start();
        t15.start();
    }
}

/*結果:
myThread:2
myThread:1
myThread:3
myThread:4
myThread:7
myThread:8
myThread:11
myThread:12
myThread:15
myThread:13
myThread:14
myThread:5
myThread:6
myThread:9
myThread:10
 
*/

Runnable介面構造執行緒

java是單基礎,繼承Thread類有侷限性,所以更多的是使用Runnable介面去新建執行緒,Thread類有構造方法使用Runnable介面新建執行緒。

public class RunableTest implements Runnable {

    @Override
    public void run() {
        System.out.println("Runable執行緒執行中:"+Thread.currentThread().getName());
    }

    public static void main(String[] arg){
        RunableTest runableTest = new RunableTest();
        Thread thread = new Thread(runableTest);
        thread.start();
        System.out.println("mainThread:"+Thread.currentThread().getName() );
    }
}

例項變數與執行緒安全

例項變數不共享

執行緒間變數不共享,資料不共享情況:

public class ShareThread extends Thread{
    private int count = 5;
    public ShareThread(String name){
        super();
        this.setName(name);
    }
    @Override
    public void run(){
        super.run();
        while (count >0){
            count--;
            System.out.println("由"+Thread.currentThread().getName()+"計算,count="+count);
        }
    }

    public static void main(String[] args){
        ShareThread shareThread1 = new ShareThread("A");
        ShareThread shareThread2 = new ShareThread("B");
        ShareThread shareThread3 = new ShareThread("C");
        shareThread1.start();
        shareThread2.start();
        shareThread3.start();
    }
}

/*
由A計算,count=4
由B計算,count=4
由B計算,count=3
由B計算,count=2
由B計算,count=1
由B計算,count=0
由A計算,count=3
由A計算,count=2
由A計算,count=1
由A計算,count=0
由C計算,count=4
由C計算,count=3
由C計算,count=2
由C計算,count=1
由C計算,count=0
*/

執行緒資料共享

共享資料情況就是多個執行緒可以訪問同一個變數。

public class ShareThread1 extends Thread {
    private int count  = 10;

    @Override
    synchronized public void run(){
        super.run();
        count--;
        //不要使用for語句,因為使用同步後執行緒就沒有執行機會了
        //一直由執行緒進行減法運算
        System.out.println("由"+Thread.currentThread().getName()+"計算,count="+count);
    }

    public static void main(String[] args){
        ShareThread1 thread1 = new ShareThread1();
        Thread a = new Thread(thread1,"A");
        Thread b = new Thread(thread1,"B");
        Thread c = new Thread(thread1,"C");
        Thread d = new Thread(thread1,"D");
        Thread e = new Thread(thread1,"E");
        Thread f = new Thread(thread1,"F");
        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
        f.start();
    }

}


/*結果:
由A計算,count=9
由D計算,count=8
由E計算,count=7
由F計算,count=6
由C計算,count=5
由B計算,count=4
*/

synchronized關鍵字表示執行多個執行緒時以排隊的方式進行處理。執行緒執行時會上鎖,執行完畢後會解鎖,執行緒呼叫run()方法前會請求執行緒鎖,若已經上鎖,則會不斷請求執行緒鎖。

System.out.println()使用時可能會發生“非執行緒安全”問題,裡面列印i--時,會先執行i--,然後列印結果,造成執行緒安全問題。

public class ShareThread2 extends Thread {
    private int i = 5;
    @Override
    public void run(){
        System.out.println("i="+ (i--) +",threadName="+Thread.currentThread().getName());
    //i--在println之前執行,故可能發生非執行緒安全問題
    }

    public static void main(String[] args) {
        ShareThread2 run = new ShareThread2();
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);
        Thread t3 = new Thread(run);
        Thread t4 = new Thread(run);
        Thread t5 = new Thread(run);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

/*
i=4,threadName=Thread-1
i=5,threadName=Thread-3
i=2,threadName=Thread-5
i=5,threadName=Thread-4
i=3,threadName=Thread-2

*/

常用函式

currentThread()方法

currentThread返回程式碼段被哪個執行緒呼叫的資訊。

public class CountOpertrate extends Thread {
    public CountOpertrate(){
        System.out.println("CountOpertate-build-start");
        System.out.println("Thread.currentThread().getName() = "+Thread.currentThread().getName());
        System.out.println("this.getName()"+this.getName());
        System.out.println("CountOpertrate-build-end");
    }

    @Override
    public void run(){
        System.out.println("run-start");
        System.out.println("Thread.currentThread().getName() = "+Thread.currentThread().getName());
        System.out.println("this.getName()"+this.getName());
        System.out.println("run-end");
    }


    public static void main(String[] args) {
        CountOpertrate countOpertrate = new CountOpertrate();
        Thread t = new Thread(countOpertrate);
        t.setName("TEST");
        t.start();
    }

/*result:
CountOpertate-build-start
Thread.currentThread().getName() = main
this.getName()Thread-0
CountOpertrate-build-end
run-start
Thread.currentThread().getName() = TEST
this.getName()Thread-0
run-end
*/

上述程式碼顯示,Count構建時時用的main執行緒,run是跑在TEST執行緒上。

isAlive()方法

isAlive方法是判斷當前執行緒是處於活動狀態。

public class IsAliveTest extends Thread {
    @Override
    public void run() {
        System.out.println("run = "+this.isAlive());
    }

    public static void main(String[] args) throws InterruptedException {
        IsAliveTest i = new IsAliveTest();
        System.out.println("start =="+i.isAlive());
        i.start();
        Thread.sleep(1000);
        System.out.println("end =="+i.isAlive());
    }
}

/*result:
start ==false
run = true
end ==false
*/

若將執行緒物件以構造引數傳遞給Thread物件進行start,結果會有差異。

public class IsAliveTest1 extends Thread {

    public IsAliveTest1(){
        System.out.println("IsAliveTest1-Start");
        System.out.println("Thread.currentThread().getName() = "+Thread.currentThread().getName());
        System.out.println("Thread.currentThread().isAlive() = "+Thread.currentThread().isAlive());
        System.out.println("this.getName() = "+this.getName());
        System.out.println("this.isAlive() = "+this.isAlive());
        System.out.println("IsAliveTest1-end");
    }
    @Override
    public void run(){
        System.out.println("run-Start");
        System.out.println("Thread.currentThread().getName() = "+Thread.currentThread().getName());
        System.out.println("Thread.currentThread().isAlive() = "+Thread.currentThread().isAlive());
        System.out.println("this.getName() = "+this.getName());
        System.out.println("this.isAlive() = "+this.isAlive());
        System.out.println("run-end");
    }

    public static void main(String[] args) throws InterruptedException {
        IsAliveTest1 test1 = new IsAliveTest1();
        Thread t1 = new Thread(test1);
        System.out.println("main bigin t1 isAlive = "+t1.isAlive());
        t1.setName("AAA");
        t1.start();
        Thread.sleep(1000);
        System.out.println("main end t1 isAlive = "+t1.isAlive());
    }
}

/*result:
IsAliveTest1-Start
Thread.currentThread().getName() = main
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
IsAliveTest1-end
main bigin t1 isAlive = false
run-Start
Thread.currentThread().getName() = AAA
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
run-end
main end t1 isAlive = false
*/

sleep()方法

sleep()方法是在括號中毫秒內使正在執行的執行緒暫停執行的方法,正在執行的執行緒是this.currentThread()返回的執行緒。

public class sleepTest extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("run threadName = "+this.getName()+"-begin");
            Thread.sleep(2000);
            System.out.println("run ThreadName = "+this.getName()+"-end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        sleepTest test = new sleepTest();
        System.out.println("begin = "+ System.currentTimeMillis());
        test.run();
        //test.start();
        System.out.println("end = "+System.currentTimeMillis());
    }
}

/*直接用run()方法
begin = 1521341785159
run threadName = Thread-0-begin
run ThreadName = Thread-0-end
end = 1521341787160
*/
/*使用start()方法
begin = 1521341902632
end = 1521341902632
run threadName = Thread-0-begin
run ThreadName = Thread-0-end

main和sleepTest執行緒是非同步的,所以先列印時間
*/

停止執行緒

interrupt()方法

interrupt方法並不是立刻停止執行緒。而是在當前執行緒中打一個停止標記。

public class InterruptTest extends Thread {

    @Override
    public void run() {
        super.run();
        for (int i = 0; i<50000;i++){
            System.out.println("i = "+ (i+1));
        }
    }

    public static void main(String[] args) {
        try {
            InterruptTest test = new InterruptTest();
            test.start();
            Thread.sleep(2000);
            Thread.interrupted();
        } catch (InterruptedException e) {
            System.out.println("main-catch");
            e.printStackTrace();
        }
    }
}
/*
無法停止,列印50000條記錄
*/

判斷執行緒是否是停止狀態

interrupted()方法,測試當前執行緒是否已經是中斷狀態,執行後將狀態標誌改為false。
isInterrupted()方法,測試執行緒物件是否已經為中斷狀態,但不清除狀態標誌。

異常法停止執行緒

可以使用isInterrupted方法判斷執行緒停止標誌狀態並丟擲InterruptedException,使用interrupt()方法停止執行緒後,因為接收到停止狀態碼,丟擲異常進入catch分支,繼而終止執行緒。

public class StopThreadTest extends Thread {

    @Override
    public void run() {
        super.run();
        try {
            for (int i=0;i<1000000;i++){
                if (this.isInterrupted()){
                    System.out.println("已是停止狀態,執行緒退出!");
                    throw new InterruptedException();
                }
                System.out.println("i = "+(i+1));
            }
            System.out.println("for下面的");
        } catch (InterruptedException e) {
            System.out.println("執行緒run()方法catch!執行緒異常終止");
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

        try {
            StopThreadTest test = new StopThreadTest();
            test.start();
            Thread.sleep(1000);
            test.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main  catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }

}

/*result:
... ...
i = 274280
i = 274281
i = 274282
i = 274283
i = 274284
end!
已是停止狀態,執行緒退出!
執行緒run()方法catch!執行緒異常終止
java.lang.InterruptedException
    at com.tz.StopThread.StopThreadTest.run(StopThreadTest.java:15)

*/

沉睡中停止程式

執行緒在sleep狀態下停止,會直接報異常,並進入catch退出,有兩種情況,一個是先sleep再interrupt,還有就是先interrupt再停止。

//先sleep

public class StopSleep1 extends Thread{

    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run-begin");
            Thread.sleep(200000);
            System.out.println("run-end");
        } catch (InterruptedException e) {
            System.out.println("在沉睡中停止,run()進入catch  "+this.isInterrupted());
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        try {
            StopSleep1 sleep1 = new StopSleep1();
            sleep1.start();
            Thread.sleep(200);
            sleep1.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main-catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

/*result:
run-begin
end!
在沉睡中停止,run()進入catch  false
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.tz.StopThread.StopSleep1.run(StopSleep1.java:13)
*/
//後sleep

public class StopSleep2 extends Thread {

    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0;i<100000;i++){
                System.out.println("i = "+(i+1));
            }
            System.out.println("run-begin");
            Thread.sleep(200000);
            System.out.println("run-end");
        } catch (InterruptedException e) {
            System.out.println("先停止再遇到sleep,run()進入catch  "+this.isInterrupted());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

            StopSleep2 sleep2 = new StopSleep2();
            sleep2.start();
            sleep2.interrupt();
            System.out.println("end!");
    }

}

/*result:
i = 99997
i = 99998
i = 99999
i = 100000
run-begin
先停止再遇到sleep,run()進入catch  false
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.tz.StopThread.StopSleep2.run(StopSleep2.java:16)
*/

暴力停止執行緒

使用stop方法停止執行緒,這個方法很暴力。

public class StopThread 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) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            StopThread thread = new StopThread();
            thread.start();
            Thread.sleep(8000);
            thread.stop();
            System.out.println("stop暴力停止");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

stop方法已經作廢,儘量不使用!!!

stop方法釋放鎖,會造成資料不一致的結果。

public class StopThread1 extends Thread {

    private SynchronizedObject object;

    public StopThread1(SynchronizedObject object){
        super();
        this.object = object;
    }

    @Override
    public void run() {
        object.printString("b","bb");
    }


    public static void main(String[] args) {

        try {
            SynchronizedObject object = new SynchronizedObject();
            StopThread1 thread1 = new StopThread1(object);
            thread1.start();
            Thread.sleep(500);
            thread1.stop();
            System.out.println("object.getUsername()="+object.getUsername());
            System.out.println("object.getPassword()="+object.getPassword());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

/*result:
object.getUsername()=b
object.getPassword()=aa
*/

return 停止執行緒

可以將interrupt()方法與return結合實現停止執行緒。

public class ReturnStopThread extends Thread{

    @Override
    public void run() {
        while(true){
            if (this.isInterrupted()){
                System.out.println("停止!");
                return;
            }
            System.out.println("timer = "+System.currentTimeMillis());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReturnStopThread thread = new ReturnStopThread();
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }
}

/*result:
... ...
timer = 1521358261861
timer = 1521358261861
timer = 1521358261861
timer = 1521358261861
timer = 1521358261861
timer = 1521358261861
timer = 1521358261861
停止!
*/

建議還是使用拋異常來停止程式,因為拋異常可以通過catch語句將執行緒停止事件上拋,是執行緒停止事件得以傳播。

暫停執行緒

暫停執行緒意味著次現場可以恢復執行,在Java多執行緒中可以使用suspend()方法暫停執行緒,使用resume()方法恢復執行緒的執行。

public class SuspendTestThread extends Thread {
    private long i = 0;
    public long getI(){
        return i;
    }

    public void setI(long i) {
        this.i = i;
    }

    @Override
    public void run() {
        while(true){
            i++;
        }
    }


    public static void main(String[] args) {
        try {
            SuspendTestThread thread = new SuspendTestThread();
            thread.start();
            Thread.sleep(1000);
            //A段
            thread.suspend();
            System.out.println("執行緒暫停!");
            System.out.println("A= " +System.currentTimeMillis()+" i="+thread.getI());
            Thread.sleep(1000);
            System.out.println("A= " +System.currentTimeMillis()+" i="+thread.getI());

            //B段
            thread.resume();
            Thread.sleep(1000);
            System.out.println("執行緒喚醒!");
            System.out.println("B= " +System.currentTimeMillis()+" i="+thread.getI());
            Thread.sleep(1000);
            System.out.println("B= " +System.currentTimeMillis()+" i="+thread.getI());

            //c段
            thread.suspend();
            System.out.println("執行緒又暫停");
            System.out.println("C= " +System.currentTimeMillis()+" i="+thread.getI());
            Thread.sleep(1000);
            System.out.println("C= " +System.currentTimeMillis()+" i="+thread.getI());

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/*result:
執行緒暫停!
A= 1521516350803 i=620113660
A= 1521516351803 i=620113660
執行緒喚醒!
B= 1521516352804 i=1259895883
B= 1521516353804 i=1901121177
執行緒又暫停
C= 1521516353804 i=1901176584
C= 1521516354804 i=1901176584

*/

明顯執行緒在A和C段暫停執行了,在B段喚醒之後又能重新執行。

suspend和rusume的缺點

  1. 獨佔

使用執行緒暫停時,如果使用不當,容易造成對公共的同步物件的獨佔,導致其他執行緒無法訪問公共同步物件。

//model.class
public class SynchronizedObject {
    synchronized public void printString(){
        System.out.println("begin");
        if (Thread.currentThread().getName().equals("a")){
            System.out.println("a執行緒永久陷入沉睡!");
            Thread.currentThread().suspend();
        }
        System.out.println("end");
    }
}

public class SuspendTestThread1 extends Thread {
    public static void main(String[] args) {
        try {
            final SynchronizedObject object = new SynchronizedObject();
            Thread thread1 = new Thread(){
                @Override
                public void run() {
                    object.printString();
                }
            };
            thread1.setName("a");
            thread1.start();
            Thread.sleep(1000);
            Thread thread2 = new Thread(){
                @Override
                public void run() {
                    System.out.println("thraed2啟動,但進入不了printString()方法");
                    System.out.println("因為printString()方法被a執行緒鎖定並獨佔了");
                    object.printString();
                }
            };
            thread2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 /*result:
 begin
a執行緒永久陷入沉睡!
thraed2啟動,但進入不了printString()方法
因為printString()方法被a執行緒鎖定並獨佔了
 */

  1. 不同步
    因為執行緒暫停可能會導致資料不同步的情況。
public class MyObject {
    private String username = "l";
    private String password = "ll";
    public void setValue(String username,String password){
        this.username = username;
        if (Thread.currentThread().getName().equals("a")){
            System.out.println("停止a執行緒!");
            Thread.currentThread().suspend();
        }
        this.password = password;
    }
    public void printUsernamePassword(){
        System.out.println(username+"  "+password);
    }
}


public class SuspendTestThread2 extends Thread {
    public static void main(String[] args) throws InterruptedException {
        final MyObject myObject = new MyObject();
        Thread thread1 = new Thread(){
            @Override
            public void run() {
                myObject.setValue("a","aa");
            }
        };
        thread1.setName("a");
        thread1.start();
        Thread.sleep(500);
        Thread thread2 = new Thread(){
            @Override
            public void run(){
                myObject.printUsernamePassword();
            }
        };
        thread2.start();
    }
}


/*result: 
停止a執行緒!
a  ll
*/

suspend()和resume()方法已經廢棄,不建議使用,可以研究。

yield()方法

yield()方法是讓當前執行緒放棄cpu資源,但放棄的時間不確定,可能剛剛放棄就立刻獲得cpu資源。

public class YieldTestThread extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        int count = 0;
        for (int i = 0;i < 50000000; i++){
            //Thread.yield();
            count = count + (i+1);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("用時:"+(endTime-beginTime)+"毫秒");
    }


    public static void main(String[] args) {
        YieldTestThread thread = new YieldTestThread();
        thread.start();
    }
}


/*result1:(不加yield)
用時:18毫秒
*/

/*result2:(加yield)
用時:3362毫秒
*/

執行緒優先順序

執行緒可以劃分優先順序,從1-10級,其他會報錯。
執行緒的優先順序具有承繼性。
優先順序規則,總是大部分先執行優先順序高的執行緒。

//執行緒1
public class PriorityTestThread extends Thread{
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        long addResult = 0;
        for (int j = 0;j < 10;j++){
            for(int i = 0;i<50000;i++){
                Random random = new Random();
                random.nextInt();
                addResult = addResult+1;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("* * * * * * thread 1 use time="+(endTime - beginTime));
    }
}

//執行緒2
public class PriorityTestThread1 extends Thread {

    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        long addResult = 0;
        for (int j = 0;j < 10;j++){
            for(int i = 0;i<50000;i++){
                Random random = new Random();
                random.nextInt();
                addResult = addResult+1;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("* * * * * * thread 2 use time="+(endTime - beginTime));
    }
}

public class Run {
    public static void main(String[] args) {
        for (int i = 0;i < 100;i++){
            PriorityTestThread thread1 = new PriorityTestThread();
            thread1.setPriority(10);
            thread1.start();
            PriorityTestThread1 thread2 = new PriorityTestThread1();
            thread2.setPriority(1);
            thread2.start();
        }
    }

}

/*result:
... ...
* * * * * * thread 1 use time=6197
* * * * * * thread 1 use time=6207
* * * * * * thread 1 use time=6252
* * * * * * thread 1 use time=6270
* * * * * * thread 2 use time=6870
* * * * * * thread 2 use time=6524
* * * * * * thread 2 use time=7036
* * * * * * thread 1 use time=7522
* * * * * * thread 1 use time=6448
* * * * * * thread 2 use time=7035
* * * * * * thread 2 use time=7223
* * * * * * thread 2 use time=7025
* * * * * * thread 1 use time=7776
* * * * * * thread 1 use time=6747
* * * * * * thread 2 use time=7261
* * * * * * thread 1 use time=7939
... ...
*/

優先順序高的不是一定先執行。

守護執行緒

守護執行緒是一種特殊執行緒,特性有“陪伴”的含義,當程式中不存在非守護程式時,守護程式就自動銷燬了。典型的守護程式就是垃圾回收執行緒(垃圾回收器 GC)

public class DaemonTestThread 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) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            DaemonTestThread thread = new DaemonTestThread();
            thread.setDaemon(true);
            thread.start();
            Thread.sleep(5000);
            System.out.println("我離開Thread物件也不再列印了,也就是停止了!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
//執行緒thread為主執行緒的守護程式,主執行緒停止守護程式也結束。

/*result:
i = 1
i = 2
i = 3
i = 4
i = 5
我離開Thread物件也不再列印了,也就是停止了!
*/

物件及變數的併發訪問

synchronzed同步方法

"非執行緒安全"會在多個執行緒對同一個物件中的例項變數進行併發訪問時發生產生"髒讀",也就是取到的資料其實是被更改過的。而執行緒安全就是以獲得的例項變數的值是經過同步處理的,不會出現髒讀現象。

方法內資料為執行緒安全

"非執行緒安全"問題存在於"例項變數"中,如果是方法內部私有變數則不存在"非執行緒安全問題"。

public class HasSelfPrivateNum {
    public void addI(String username){
        try {
            int num = 0;
            if (username.equals("a")){
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            }else {
                num = 200;
                System.out.println("b set over!");
                Thread.sleep(2000);
            }
            System.out.println(username + " num = "+num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


public class ThreadA extends Thread {
    private HasSelfPrivateNum numRef;
    public ThreadA(HasSelfPrivateNum numRef){
        super();
        this.numRef = numRef;
    }

    @Override
    public void run() {
        super.run();
        numRef.addI("a");
    }
}



public class ThreadB extends Thread {
    private HasSelfPrivateNum numRef;
    public ThreadB(HasSelfPrivateNum numRef){
        super();
        this.numRef = numRef;
    }

    @Override
    public void run() {
        super.run();
        numRef.addI("b");
    }

}



public class Run {
    public static void main(String[] args) {
        HasSelfPrivateNum numRef = new HasSelfPrivateNum();
        ThreadA threadA = new ThreadA(numRef);
        threadA.start();
        ThreadB threadB = new ThreadB(numRef);
        threadB.start();
    }
}



/*result:
a set over!
b set over!
a num = 100
b num = 200

*/

例項變數非執行緒安全

若多個執行緒訪問一個物件例項中的例項變數。則可能發生“非執行緒安全”問題。
用執行緒訪問的物件中如果有多個例項變數,則執行的結果有可能出現交叉的情況。
如果物件僅有一個例項變數,則有可能出現覆蓋的情況。

public class HasSelfPrivateNum{
    private int num = 0;
    
    //addI()方法前加上synchronized關鍵字,避免“非執行緒安全問題”
   synchronized public void addI(String username){
        try {
            if (username.equals("a")){
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            }else {
                num = 200;
                System.out.println("b set over!");
                Thread.sleep(2000);
            }
            System.out.println(username + " num = "+num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


public class ThreadA extends Thread {
    private HasSelfPrivateNum numRef;
    public ThreadA(HasSelfPrivateNum numRf){
        super();
        this.numRef = numRf;
    }

    @Override
    public void run() {
        super.run();
        numRef.addI("a");
    }
}


public class ThreadB extends Thread {
    private HasSelfPrivateNum numRef;
    public ThreadB(HasSelfPrivateNum numRf){
        super();
        this.numRef = numRf;
    }

    @Override
    public void run() {
        super.run();
        numRef.addI("b");
    }

}


public class Run {
    public static void main(String[] args) {
        HasSelfPrivateNum numRef = new HasSelfPrivateNum();
        ThreadA threadA = new ThreadA(numRef);
        threadA.start();
        ThreadB threadB = new ThreadB(numRef);
        threadB.start();
    }
}


/*不加synchronized關鍵字:
a set over!
b set over!
b num = 200
a num = 200
*/


/*加synchronized關鍵字:
a set over!
a num = 100
b set over!
b num = 200
*/

多個物件多個鎖

synchronized關鍵字取得的鎖都物件鎖,哪個執行緒先執行帶有synchronized關鍵字的方法就先獲得物件鎖,其他執行緒只能依次等待執行完成。

public class LockTestObject {
   synchronized public void methodA(){
       try {
           System.out.println("Begin methodA threadName = "+Thread.currentThread().getName());
           Thread.sleep(5000);
           System.out.println("methodA end! endTime = "+System.currentTimeMillis());
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }

  synchronized public void methodB(){
       try {
           System.out.println("Begin methodB threadName = "+Thread.currentThread().getName());
           Thread.sleep(5000);
           System.out.println("methodB end! endTime = "+System.currentTimeMillis());
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}



public class LockThreadA extends Thread {
   private LockTestObject object;
   public LockThreadA(LockTestObject object){
       super();
       this.object = object;
   }

   @Override
   public void run() {
       super.run();
       object.methodA();
   }
}



public class LockThreadB extends Thread {
   private LockTestObject object;
   public LockThreadB(LockTestObject object){
       super();
       this.object = object;
   }

   @Override
   public void run() {
       super.run();
       object.methodB();
   }
}


public class Run {
   public static void main(String[] args) {
       LockTestObject object = new LockTestObject();
       LockThreadA threadA = new LockThreadA(object);
       threadA.setName("A");
       LockThreadB threadB = new LockThreadB(object);
       threadB.setName("B");
       threadA.start();
       threadB.start();
   }
}


/*methodA方法不加synchronized關鍵字
Begin methodB threadName = B
Begin methodA threadName = A
methodB end! endTime = 1521719664578
methodA end! endTime = 1521719664579
*/

/*methodA方法加上synchronized關鍵字
Begin methodA threadName = A
methodA end! endTime = 1521719556410
Begin methodB threadName = B
methodB end! endTime = 1521719561411
*/

髒讀

所謂髒讀是在對去例項變數時該變數已被其他執行緒改過,讀出資料有誤。

public class PublicVar {
    public String userName = "A";
    public String password = "AA";
    synchronized public void setValue(String userName,String password){
        try {
            this.userName = userName;
            Thread.sleep(5000);
            this.password = password;
            System.out.println("setValue method thread name = "+Thread.currentThread().getName()+" userName = "+userName+" password = "+password);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void getValue(){
        System.out.println("setValue method thread name = "+Thread.currentThread().getName()+" userName = "+userName+" password = "+password);
    }
}


public class DirtyReadTestThread extends Thread{
    private PublicVar publicVar;
    public DirtyReadTestThread(PublicVar publicVar){
        super();
        this.publicVar = publicVar;
    }

    @Override
    public void run() {
        super.run();
        publicVar.setValue("B","BB");
    }
}


public class Run {
    public static void main(String[] args) {
        try {
            PublicVar publicVar = new PublicVar();
            DirtyReadTestThread thread = new DirtyReadTestThread(publicVar);
            thread.start();
            Thread.sleep(200);
            publicVar.getValue();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


/*result:
setValue method thread name = main userName = B password = AA
setValue method thread name = Thread-0 userName = B password = BB
*/

如上所示,main執行緒出現了髒讀,因為getValue()方法不是同步的,只需在getValue前加上synchronized關鍵字,即可保持資料同步性。

 synchronized public void getValue(){
        System.out.println("setValue method thread name = "+Thread.currentThread().getName()+" userName = "+userName+" password = "+password);
    }
    
/*result:
setValue method thread name = Thread-0 userName = B password = BB
setValue method thread name = main userName = B password = BB
*/

當執行緒呼叫物件包含的synchronized方法時獲取了物件的X鎖,但別的執行緒可以呼叫該實體非synchronized方法。

synchronized 鎖重入

一個執行緒多次請求synchronized方法鎖時,可以重複獲得方法所在的物件實體的X鎖
鎖重入,即可重複獲得內部鎖。

public class Service {
    synchronized public void service1(){
        System.out.println("service1");
        service2();
    }

    synchronized public void service2(){
        System.out.println("service2");
        service3();
    }
    synchronized public void service3(){
        System.out.println("service3");
    }
}

public class LockReentryTestThread  extends Thread {
    @Override
    public void run() {
        Service service = new Service();
        service.service1();
    }
}


public class Run {
    public static void main(String[] args) {
        LockReentryTestThread thread = new LockReentryTestThread();
        thread.start();
    }
}

/*result:
service1
service2
service3
*/

service類中鎖就重入了,三個service方法相互呼叫。

鎖重入也支援在父子類間的鎖重用。

出現異常,鎖自動釋放,其他執行緒繼續呼叫。

synchronized方法的弊端

導致程式等待時間較長,失去多執行緒的意義,導致程式響應時間過長。
synchronized同步塊可以解決這個問題。

synchronized同步程式碼塊

當兩個併發的執行緒訪問同一個物件object中的synchronized(this)同步塊時,一段時間內只有一個執行緒能訪問並執行,另一個執行緒必須等待前一個執行緒執行完畢這個程式碼塊之後,才能執行這塊程式碼。

使用同步synchronized 程式碼塊時,同一個object的同步程式碼塊使用同一個物件監視器,執行一個同步塊時物件中其他同步塊會被阻塞。

將任意物件作為物件監視器

鎖非this物件的優點是:若在一個類中有很多個synchronized方法,這時雖然能實現同步,但會收到阻塞,影響執行效率;若使用同步程式碼塊鎖非this物件,則synchronized(非this)程式碼塊中的程式與同步方法是非同步的,不與其他鎖this的同步方法爭搶this鎖。則可提高執行效率。

靜態同步synchronized方法與synchronized(class)程式碼塊。

關鍵字還可以作用在static靜態方法上,是對方法所在的類.class持鎖,而不是對一個物件上鎖。
synchronized程式碼塊也可以對class類上鎖,實現同步。synchronized(xxx.class)。

資料型別String的常量池特性

由於JVM中String資料型別的常量池特性 a==b 返回true,所以不使用String物件作為物件監視器(物件鎖)。

同步synchronized方法無限等待與解決

synchronized同步方法容易造成死迴圈,是形成陷入死鎖。同步塊可以解開這個死鎖問題,死鎖執行緒依舊跳不出,但其他執行緒可獲得鎖。

多執行緒的死鎖

synchronized巢狀程式碼塊將帶來死鎖。

進入Cmd 輸入 jsp 查詢Run的id值 在輸入 jstack -l 19560 可檢視程式執行死鎖情況

內建類與靜態內建類

鎖物件的改變

public class MyService {
    private String lock = "123";
    public void testMethod() {
        try {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + "  begin  " + System.currentTimeMillis());
                lock = "456";
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + "  end  " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


public class ThreadA extends Thread {
    private MyService service;
    public ThreadA(MyService service) {
        super();
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }
}


public class ThreadB extends Thread{
    private MyService service;
    public ThreadB(MyService service) {
        super();
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }
}


public class Run1 {
    public static void main(String[] args) throws InterruptedException {
        MyService service = new MyService();
        ThreadA threadA = new ThreadA(service);
        threadA.setName("A");

        ThreadB threadB = new ThreadB(service);
        threadB.setName("B");
        threadA.start();
        //Thread.sleep(50 );
        threadB.start();
    }
}


/*延遲50毫秒,爭搶兩個鎖
A  begin  1523325785537
B  begin  1523325785585
A  end  1523325787539
B  end  1523325787585
*/

/*不延遲,爭搶一個鎖
A  begin  1523325815403
A  end  1523325817403
B  begin  1523325817403
B  end  1523325819404
*/

只要鎖物件不變,即使物件屬性改變依舊同步,執行緒還是爭搶一個鎖。

相關文章