java Thread深入了解(二)

synchronized方法和synchronized代碼段

synchronized方法 只有一個線程能訪問,只有這個方法執(zhí)行完之后其他線程才能訪問
synchronized方法的鎖是當前對象,也就是如果new多次是不能阻止多個線程訪問代碼的

public class SyncTest {
    
    /**
     * 對于SyncTest的對象 只有一個線程能訪問
     * 對于不同的SyncTest的對象可以有多個線程訪問
     */
    public  synchronized void say(){
        System.out.println("hello get the lock!");
        //休眠200s 不釋放鎖
        try {
            Thread.sleep(200 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 與synchronized方法相同
     */
    public  void say(){
        synchronized(this) {
            System.out.println("hello get the lock!");
            //休眠200s 不釋放鎖
            try {
                Thread.sleep(200 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 同一時間只有一個線程能訪問
     * 與synchronized方法不同
    **/
    public  void say(){
        synchronized(SyncTest.class) {
            System.out.println("hello get the lock!");
            //休眠200s 不釋放鎖
            try {
                Thread.sleep(200 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

最為線程安全類 最常見的做法就是加synchronized方法

StringBuilder
StringBuffer
HashTable
HashMap

Thread類常用方法

名稱 new Thread(String name) new Thread(Runnable run,String name)

獲取當前Thread Thread.currentThread();

獲取當前所有Thread的數(shù)量 Thread.activeCount();

線程變量ThreadLocal

ThreadLocal是一個特殊的模板變量 每個線程獲取到的都是自己的值

public class ThreadLocalTest{

    private static ThreadLocal<ThreadLocalTest> threadLocal=new ThreadLocal<>();
    private static ThreadLocalTest mainThreadLocal;

    /**
     * 創(chuàng)建當前線程的ThreadLocal對象
     */
    public static void prepare(){
        if(threadLocal.get()==null){
            threadLocal.set(new ThreadLocalTest());
        }
    }

    /**
     * 主線程中調用
     */
    public static void prepareMain(){
        if(mainThreadLocal!=null){
            throw new RuntimeException("只有一個線程可以調用prepareMain");
        }
        mainThreadLocal=new ThreadLocalTest();
        if(threadLocal.get()==null){
            threadLocal.set(mainThreadLocal);
        }
    }

    public static ThreadLocalTest getMain(){
        return mainThreadLocal;
    }

    public static ThreadLocalTest myThreadTest(){
        return threadLocal.get();
    }

    private ThreadLocalTest(){

    }

}

其實現(xiàn)原理 利用的是Thread.currentThread();

concurrent包的CountDownLatch

一個輔助類,初始化的時候指定數(shù)據(jù)個數(shù),沒調用一次countDown()數(shù)字減少一個
await方法會阻塞 直到CountDownLatch里的數(shù)字為0

CountDownLatch countDownLatch=new CountDownLatch(100);
for(int i=0;i<100;i++){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(200);
                System.out.println(Thread.currentThread().getName()+" done!");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
try {
    countDownLatch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("所有線程完成了!");

線程A , B ,C。 A,B運行完后運行C

CountDownLatch countDownLatch=new CountDownLatch(2);
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" done !");
        countDownLatch.countDown();
    }
},"A").start();
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" done !");
        countDownLatch.countDown();
    }
},"B").start();
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" done !");
    }
},"C").start();

線程池初步

long startTime=System.currentTimeMillis();
CountDownLatch countDownLatch=new CountDownLatch(65535);
for(int i=0;i<65535;i++){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(200);
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
try {
    countDownLatch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("所有線程完成了!"+(System.currentTimeMillis()-startTime)+"ms");

上面的代碼預計消耗時間是200ms但是 實際遠遠超出了我們的預期,這是因為新建線程消耗了一部分時間,cpu擁擠,并不會有那么多線程同時運行,會排隊一會。
通過線程池可以優(yōu)化上述代碼的速度

/*
 * 空閑線程
*/
public class IdleThread extends Thread {

    public LinkedBlockingQueue<Runnable> queue;
    public boolean started = true;

    public IdleThread(LinkedBlockingQueue<Runnable> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (started) {
            try {
                Runnable runnable = queue.poll(100, TimeUnit.MILLISECONDS);
                if(runnable!=null)
                    runnable.run();
            } catch (InterruptedException e) {
            }
        }
    }

    public void kill() {
        started = false;
    }
}

/**
 * 基礎線程池
 */
public class ThreadPool {

    /**
     * 池最小大小
     */
    private int minSize;

    /**
     * 池最大大小
     */
    private int maxSize;


    LinkedBlockingQueue<Runnable> tasks;

    List<IdleThread> idleThreads;

    public ThreadPool(int size){
        this.maxSize=size;
        this.minSize=size;
        init();
    }

    private void init(){
        tasks=new LinkedBlockingQueue<>(minSize);
        idleThreads=new ArrayList<>(minSize);
        for(int i=0;i<minSize;i++){
            IdleThread thread=new IdleThread(tasks);
            idleThreads.add(thread);
            thread.start();
        }
    }

    public void execute(Runnable runnable) throws InterruptedException {
        tasks.put(runnable);
    }

    public void shutdown(){
        try {
            for (IdleThread idleThread : idleThreads) {
                idleThread.kill();
                idleThread.interrupt();
            }
        }catch (Exception e){
            e.printStackTrace();;
        }
        tasks.clear();
    }

    public void waitForAll(){
        while(tasks.size()>0){
            try {
                Thread.sleep(0,1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

通過上述兩類 重寫一下上面的代碼

long startTime=System.currentTimeMillis();
CountDownLatch countDownLatch=new CountDownLatch(65535);
ThreadPool threadPool=new ThreadPool(9000);
for(int i=0;i<65535;i++){
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(200);
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}
try {
    countDownLatch.await();
    threadPool.shutdown();
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("所有線程完成了!"+(System.currentTimeMillis()-startTime)+"ms");

可以看到速度比那個優(yōu)化很多

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 一.synchronized方法和synchronized代碼塊 synchronized方法 只有一個線程能訪問...
    Charon_Pluto閱讀 381評論 0 0
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,664評論 18 399
  • 本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應的一些線程函數(shù)用法、概述等。 首先講...
    李欣陽閱讀 2,597評論 1 15
  • 喜歡綠色, 那些綠色的味道要我回想起童年的夢, 童年間嬉戲于天水之間, 是那樣的天真快樂, 那路邊的石子、 村邊的...
    佳蜜家釀蜂蜜蜂產(chǎn)品閱讀 219評論 0 0
  • 婚禮上,D深情的對小羽說:“小羽,你知道嗎?我們第一次見面的時候,我就知道,你就是我一直尋找的那個人,你終于來了。...
    王子月閱讀 327評論 0 0

友情鏈接更多精彩內容