最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

徹底搞懂Java多線程(四)

 更新時(shí)間:2021年07月03日 16:45:54   作者:保護(hù)眼睛  
這篇文章主要給大家介紹了關(guān)于Java面試題之多線程和高并發(fā)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

SimpleDateFormat非線程安全問題

實(shí)現(xiàn)1000個(gè)線程的時(shí)間格式化

package SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * user:ypc;
 * date:2021-06-13;
 * time: 17:30;
 */
public class SimpleDateFormat1 {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,10,100,
                TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(1000),new ThreadPoolExecutor.DiscardPolicy());

        for (int i = 0; i < 1001; i++) {
            int finalI = i;
            threadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    Date date = new Date(finalI * 1000);
                    myFormatTime(date);
                }
            });
        }
        threadPoolExecutor.shutdown();
    }
    private static void myFormatTime(Date date){
        System.out.println(simpleDateFormat.format(date));
    }
}

產(chǎn)生了線程不安全的問題👇:

在這里插入圖片描述

這是因?yàn)椋?/p>

在這里插入圖片描述

多線程的情況下:

在這里插入圖片描述

線程1在時(shí)間片用完之后,線程2來setTime()那么線程1的得到了線程2的時(shí)間。

所以可以使用加鎖的操作:

在這里插入圖片描述

就不會(huì)有重復(fù)的時(shí)間了

在這里插入圖片描述

但是雖然可以解決線程不安全的問題,但是排隊(duì)等待鎖,性能就會(huì)變得低

所以可以使用局部變量:

在這里插入圖片描述

也解決了線程不安全的問題:

在這里插入圖片描述

但是每次也都會(huì)創(chuàng)建新的私有變量

那么有沒有一種方案既可以避免加鎖排隊(duì)執(zhí)行,又不會(huì)每次創(chuàng)建任務(wù)的時(shí)候不會(huì)創(chuàng)建私有的變量呢?

那就是ThreadLocal👇:

ThreadLocal

ThreadLocal的作用就是讓每一個(gè)線程都擁有自己的變量。

那么選擇鎖還是ThreadLocal?

看創(chuàng)建實(shí)列對象的復(fù)用率,如果復(fù)用率比較高的話,就使用ThreadLocal。

ThreadLocal的原理

類ThreadLocal的主要作用就是將數(shù)據(jù)放到當(dāng)前對象的Map中,這個(gè)Map時(shí)thread類的實(shí)列變量。類ThreadLocal自己不管理、不存儲(chǔ)任何的數(shù)據(jù),它只是數(shù)據(jù)和Map之間的橋梁。

執(zhí)行的流程:數(shù)據(jù)—>ThreadLocal—>currentThread()—>Map。

執(zhí)行后每個(gè)Map存有自己的數(shù)據(jù),Map中的key中存儲(chǔ)的就是ThreadLocal對象,value就是存儲(chǔ)的值。每個(gè)Thread的Map值只對當(dāng)前的線程可見,其它的線程不可以訪問當(dāng)前線程對象中Map的值。當(dāng)前的線程被銷毀,Map也隨之被銷毀,Map中的數(shù)據(jù)如果沒有被引用、沒有被使用,則隨時(shí)GC回收。

ThreadLocal常用方法

在這里插入圖片描述

set(T):將內(nèi)容存儲(chǔ)到ThreadLocal

get():從線程去私有的變量

remove():從線程中移除私有變量

package ThreadLocalDemo;
import java.text.SimpleDateFormat;
/**
 * user:ypc;
 * date:2021-06-13;
 * time: 18:37;
 */
public class ThreadLocalDemo1 {
    private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
        //設(shè)置私有變量
        threadLocal.set(new SimpleDateFormat("mm:ss"));
        //得到ThreadLocal
        SimpleDateFormat simpleDateFormat = threadLocal.get();
        //移除
        threadLocal.remove();
    }
}

ThreadLocal的初始化

ThreadLocal提供了兩種初始化的方法

initialValue()和

initialValue()初始化:

package ThreadLocalDemo;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * user:ypc;
 * date:2021-06-13;
 * time: 19:07;
 */
public class ThreadLocalDemo2 {
    //創(chuàng)建并初始化ThreadLocal
    private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal() {
        @Override
        protected SimpleDateFormat initialValue() {
            System.out.println(Thread.currentThread().getName() + "執(zhí)行了自己的threadLocal中的初始化方法initialValue()");
            return new SimpleDateFormat("mm:ss");
        }
    };
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            Date date = new Date(5000);
            System.out.println("thread0格式化時(shí)間之后得結(jié)果時(shí):" + threadLocal.get().format(date));
        });
        thread1.setName("thread0");
        thread1.start();

        Thread thread2 = new Thread(() -> {
            Date date = new Date(6000);
            System.out.println("thread1格式化時(shí)間之后得結(jié)果時(shí):" + threadLocal.get().format(date));
        });
        thread2.setName("thread1");
        thread2.start();
    }
}

在這里插入圖片描述

withInitial方法初始化:

package ThreadLocalDemo;
import java.util.function.Supplier;
/**
 * user:ypc;
 * date:2021-06-14;
 * time: 17:23;
 */
public class ThreadLocalDemo3 {
    private static ThreadLocal<String> stringThreadLocal =
            ThreadLocal.withInitial(new Supplier<String>() {
                @Override
                public String get() {
                    System.out.println("執(zhí)行了withInitial()方法");
                    return "我是" + Thread.currentThread().getName() + "的ThreadLocal";
                }
            });
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            System.out.println(stringThreadLocal.get());
        });
        thread1.start();

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(stringThreadLocal.get());
            }
        });
        thread2.start();
    }
}

在這里插入圖片描述

注意:

ThreadLocal如果使用了set()方法的話,那么它的初始化方法就不會(huì)起作用了。

來看:👇

package ThreadLocalDemo;
/**
 * user:ypc;
 * date:2021-06-14;
 * time: 18:43;
 */
class Tools {
    public static ThreadLocal t1 = new ThreadLocal();
}
class ThreadA extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("在ThreadA中取值:" + Tools.t1.get());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadLocalDemo4 {
    public static void main(String[] args) throws InterruptedException {
        //main是ThreadA 的 父線程 讓main線程set,ThreadA,是get不到的
        if (Tools.t1.get() == null) {
            Tools.t1.set("main父線程的set");
        }
        System.out.println("main get 到了: " + Tools.t1.get());

        Thread.sleep(1000);
        ThreadA a = new ThreadA();
        a.start();
    }
}

在這里插入圖片描述

類ThreadLocal不能實(shí)現(xiàn)值的繼承,那么就可以使用InheritableThreadLocal了👇

InheritableThreadLocal的使用

使用InheritableThreadLocal可以使子線程繼承父線程的值

在這里插入圖片描述

在來看運(yùn)行的結(jié)果:

在這里插入圖片描述

子線程有最新的值,父線程依舊是舊的值

package ThreadLocalDemo;
/**
 * user:ypc;
 * date:2021-06-14;
 * time: 19:07;
 */
class ThreadB extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("在ThreadB中取值:" + Tools.t1.get());
            if (i == 5){
                Tools.t1.set("我是ThreadB中新set()");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadLocalDemo5 {
    public static void main(String[] args) throws InterruptedException {
        if (Tools.t1.get() == null) {
            Tools.t1.set("main父線程的set");
        }
        System.out.println("main get 到了: " + Tools.t1.get());

        Thread.sleep(1000);
        ThreadA a = new ThreadA();
        a.start();
        Thread.sleep(5000);
        for (int i = 0; i < 10; i++) {
            System.out.println("main的get是:" + Tools.t1.get());
            Thread.sleep(100);
        }
    }
}

在這里插入圖片描述

ThreadLocal的臟讀問題來看👇

package ThreadLocalDemo;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * user:ypc;
 * date:2021-06-14;
 * time: 19:49;
 */
public class ThreadLocalDemo6 {
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    private static class MyThread extends Thread {
        private static boolean flag = false;
        @Override
        public void run() {
            String name = this.getName();
            if (!flag) {
                threadLocal.set(name);
                System.out.println(name + "設(shè)置了" + name);
                flag = true;
            }
            System.out.println(name + "得到了" + threadLocal.get());
        }
    }
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0,
                TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10));

        for (int i = 0; i < 2; i++) {
            threadPoolExecutor.execute(new MyThread());
        }
        threadPoolExecutor.shutdown();
    }
}

在這里插入圖片描述

發(fā)生了臟讀:

線程池復(fù)用了線程,也復(fù)用了這個(gè)線程相關(guān)的靜態(tài)屬性,就導(dǎo)致了臟讀

那么如何避免臟讀呢?

去掉static 之后:

在這里插入圖片描述

在這里插入圖片描述

總結(jié)

本篇文章就到這里了,希望對你有些幫助,也希望你可以多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • MyBatis-Plus通過version機(jī)制實(shí)現(xiàn)樂觀鎖的思路

    MyBatis-Plus通過version機(jī)制實(shí)現(xiàn)樂觀鎖的思路

    version機(jī)制的核心思想就是,假設(shè)發(fā)生并發(fā)沖突的幾率很低,只有當(dāng)更新數(shù)據(jù)的時(shí)候采取檢查是否有沖突,而判斷是否有沖突的依據(jù)就是version的值是否被改變了,這篇文章主要介紹了MyBatis-Plus通過version機(jī)制實(shí)現(xiàn)樂觀鎖的思路,需要的朋友可以參考下
    2021-09-09
  • 為何修改equals方法時(shí)還要重寫hashcode方法的原因分析

    為何修改equals方法時(shí)還要重寫hashcode方法的原因分析

    這篇文章主要介紹了為何修改equals方法時(shí)還要重寫hashcode方法的原因分析,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解

    Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解

    這篇文章主要為大家介紹了Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • Java中Lombok常用注解分享

    Java中Lombok常用注解分享

    以前的Java項(xiàng)目中充斥了太多不友好的代碼,這些代碼不僅沒有什么技術(shù)含量,還影響代碼的美觀,所以Lombok應(yīng)運(yùn)而生了。本文和大家分享了一些Java中Lombok常用注解,需要的可以了解一下
    2023-04-04
  • Jetbrains系列產(chǎn)品重置試用思路詳解

    Jetbrains系列產(chǎn)品重置試用思路詳解

    這篇文章主要介紹了Jetbrains系列產(chǎn)品重置試用思路詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • SpringBoot項(xiàng)目打包運(yùn)行jar包的實(shí)現(xiàn)示例

    SpringBoot項(xiàng)目打包運(yùn)行jar包的實(shí)現(xiàn)示例

    本文主要介紹了SpringBoot項(xiàng)目打包運(yùn)行jar包的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-02-02
  • Java實(shí)現(xiàn)DES加密與解密,md5加密以及Java實(shí)現(xiàn)MD5加密解密類

    Java實(shí)現(xiàn)DES加密與解密,md5加密以及Java實(shí)現(xiàn)MD5加密解密類

    這篇文章主要介紹了Java實(shí)現(xiàn)DES加密與解密,md5加密以及Java實(shí)現(xiàn)MD5加密解密類 ,需要的朋友可以參考下
    2015-11-11
  • SpringBoot2.0+阿里巴巴Sentinel動(dòng)態(tài)限流實(shí)戰(zhàn)(附源碼)

    SpringBoot2.0+阿里巴巴Sentinel動(dòng)態(tài)限流實(shí)戰(zhàn)(附源碼)

    這篇文章主要介紹了SpringBoot2.0+阿里巴巴Sentinel動(dòng)態(tài)限流實(shí)戰(zhàn)(附源碼),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 詳解IDEA2021.2安裝后的配置及重裝問題

    詳解IDEA2021.2安裝后的配置及重裝問題

    這篇文章主要介紹了IDEA2021.2安裝后的配置及重裝,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • 5個(gè)并發(fā)處理技巧代碼示例

    5個(gè)并發(fā)處理技巧代碼示例

    這篇文章主要介紹了5個(gè)并發(fā)處理技巧代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10

最新評論

新疆| 雷州市| 南汇区| 阳高县| 陇川县| 京山县| 石景山区| 宜君县| 济南市| 乌什县| 五指山市| 城口县| 沙雅县| 新源县| 洪泽县| 资源县| 称多县| 鄂尔多斯市| 苍南县| 孟州市| 比如县| 晋中市| 高尔夫| 吉隆县| 台东县| 承德县| 武强县| 沾益县| 乡城县| 灵台县| 报价| 芮城县| 娱乐| 会同县| 桂东县| 斗六市| 囊谦县| 寻乌县| 临江市| 阿勒泰市| 察隅县|