多線程知識(shí)點(diǎn)synchronized wait join yield

package com.hencoder.a17_thread_interaction;

/**
 *  讀寫鎖。
 *     ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
 *     Lock readLock = lock.readLock();
 *     Lock writeLock = lock.writeLock();
 *
 */
public class WaitDemo implements TestDemo {
    private String sharedString;

    private int x=0;
    private int y=0;

    /**
     * synchronized 關(guān)鍵字是鎖定當(dāng)前的對(duì)象。
     * 被synchronized包括的代碼塊將會(huì)是一個(gè)原子性的操作,中間不會(huì)被打斷
     */
    public synchronized void add(){
        //x++ 在cpu中是分為以下兩個(gè)步驟來執(zhí)行的
        //int tmep = x + 1;
        //x = temp;
        x++;
        y++;
    }

    public void sub(){
        synchronized (this){//這個(gè) 等價(jià)于 直接在方法上面加synchronized 關(guān)鍵字
            x--;
            y--;
        }
    }


    private synchronized void initString() {
        sharedString = "rengwuxian";
        notifyAll();//必須寫在synchronized方法里
    }

    private synchronized void printString() {
        //wait()方法 會(huì)暫時(shí)丟掉synchronized鎖。直到InterruptedException或者 notify
        while (sharedString == null) {//要用while因?yàn)?Thread.interrupted()也會(huì)喚醒wait();
            try {
                wait();//必須寫在synchronized方法里,因?yàn)閣ait要釋放鎖
            } catch (InterruptedException e) {//如果線程被調(diào)用了Thread.interrupted()方法 則會(huì)拋出這個(gè)異常
                e.printStackTrace();
            }
        }
        System.out.println("String: " + sharedString);
    }

    @Override
    public void runTest() {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printString();
            }
        };
        thread1.start();
        Thread thread2 = new Thread() {
            @Override
            public void run() {

                try {
                    thread1.join();//join方法會(huì)等待thread1運(yùn)行完畢,才繼續(xù)執(zhí)行下面的代碼。
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Thread.yield();//暫時(shí)讓出cpu,執(zhí)行其他任務(wù)
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                initString();
            }
        };
        thread2.start();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容