1. 程式人生 > >java高併發(四)併發程式設計與執行緒安全

java高併發(四)併發程式設計與執行緒安全

    程式碼有多個執行緒同時執行,而這些執行緒可能會同時運行同一段程式碼,如果每次執行的結果和單執行緒執行的結果是一樣的,我們就認為是執行緒安全的。執行緒不安全就是執行緒不提供訪問保護,有可能出現多個執行緒先後更改資料,造成所得到的資料是髒資料,也可能是計算時出現錯誤。

新建專案project-1,pom.xml檔案內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.vincent</groupId>
    <artifactId>concurrency</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <es.version>6.2.3</es.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.1.4.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

新建一個註解ThreadSafe.java,我們期望的是對於一個執行緒安全的類,我們使用ThreadSafe來進行標識,因為我們後面的程式碼常常會使用執行緒安全和不安全。內容如下:

package com.vincent.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 用來標記執行緒安全的類或者寫法
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface ThreadSafe {
    String value() default "";
}

接下來定義一個執行緒不安全的註解:

/**
 * 用來標記執行緒【不安全】的類或者寫法
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface NotThreadSafe {
    String value() default "";
}

定義一個推薦的註解:

/**
 * 用來標記執行緒【推薦】的類或者寫法
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Recommend {
    String value() default "";
}

定義一個不推薦的註解:

/**
 * 用來標記執行緒【不推薦】的類或者寫法
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface NotRecommend {
    String value() default "";
}