Commit fccac5e1 by 仲光辉

init: project Initialization

parents
# Created by .ignore support plugin (hsz.mobi)
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.idea
*.iml
build
.gradle
// java,IntelliJ IDEA 插件
plugins {
id 'java'
id 'idea'
}
group 'cn.dankal.share'
description 'dankal-share-volatile'
version '1.0.0.RELEASE'
// 依赖仓库配置
repositories {
// GRADLE_USER_HOME : maven 本地仓库地址
mavenLocal()
maven {
url 'https://maven.aliyun.com/repository/public/'
}
maven {
url 'https://maven.aliyun.com/repository/spring/'
}
maven {
url 'https://maven.aliyun.com/repository/gradle-plugin'
}
maven {
url 'https://maven.aliyun.com/repository/spring-plugin'
}
mavenCentral()
}
// 编译字符集
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
// 使用的 java 版本
java.sourceCompatibility = JavaVersion.VERSION_1_8
java.targetCompatibility = JavaVersion.VERSION_1_8
// 项目依赖
dependencies {
implementation 'cn.hutool:hutool-core:5.5.4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}
// 执行测试任务
test {
useJUnitPlatform()
}
\ No newline at end of file
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://res.mercymodest.com/gradle-6.7.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
rootProject.name = 'dankal-share-volatile'
package cn.dankal.share;
/**
* DclSingletonTest
* <br/>
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/12/29
* @copyright 蛋壳创意科技 - www.dankal.cn
*/
public class DclSingletonTest {
public static void main(String[] args) {
SingletonInstance singletonInstance = SingletonInstance.getInstance();
}
}
class SingletonInstance {
private static volatile SingletonInstance singletonInstance;
private SingletonInstance() {
}
public static SingletonInstance getInstance() {
if (null == singletonInstance) {
synchronized (SingletonInstance.class) {
if (null == singletonInstance) {
singletonInstance = new SingletonInstance();
}
}
}
return singletonInstance;
}
}
package cn.dankal.share;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* VolatileKeywordTest
* <br/>
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/12/29
* @copyright 蛋壳创意科技 - www.dankal.cn
*/
public class VolatileKeywordTest {
public static void main(String[] args) throws InterruptedException {
final DataOperator dataOperator = new DataOperator();
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor("test volatile with atomic -- ");
// 计数扣减 保证 main 线程 在 20 个子线程之后执行
final CountDownLatch countDownLatch = new CountDownLatch(20);
final int threadCount = 20;
for (int i = 0; i < threadCount; i++) {
threadPoolExecutor.execute(() -> {
System.out.println(Thread.currentThread().getName() + " do incr by atomic");
final int executeCount = 1000;
for (int j = 0; j < executeCount; j++) {
dataOperator.atomicIncrNum();
}
countDownLatch.countDown();
});
}
// 等待 20 个线程执行完成
countDownLatch.await();
System.out.println("the executor result: " + dataOperator.atomicInteger2Num.get());
threadPoolExecutor.shutdown();
}
/**
* 测试 Volatile 关键字无法保证原子性
*
* @param dataOperator DataOperator
* @throws InterruptedException
*/
private static void testVolatileNonAtomic(DataOperator dataOperator) throws InterruptedException {
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor("test volatile non atomic -- ");
// 计数扣减 保证 main 线程 在 20 个子线程之后执行
final CountDownLatch countDownLatch = new CountDownLatch(20);
final int threadCount = 20;
for (int i = 0; i < threadCount; i++) {
threadPoolExecutor.execute(() -> {
final int executeCount = 1000;
for (int j = 0; j < executeCount; j++) {
dataOperator.incrNum();
}
countDownLatch.countDown();
});
}
// 等待 20 个线程执行完成
countDownLatch.await();
System.out.println("the executor result: " + dataOperator.num);
threadPoolExecutor.shutdown();
}
/**
* 获取 线程池
*
* @param threadNamePrefix 线程池线程名称前缀
* @return ThreadPoolExecutor
*/
private static ThreadPoolExecutor getThreadPoolExecutor(String threadNamePrefix) {
return new ThreadPoolExecutor(
20,
35,
10,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1 << 10),
runnable -> {
Thread thread = new Thread(runnable);
thread.setName(threadNamePrefix + thread.getId());
return thread;
}
);
}
/**
* 测试 Volatile 关键字 的 可见性
*
* @param dataOperator DataOperator
*/
private static void testVolatileVisibility(DataOperator dataOperator) {
new Thread(() -> {
try {
// 休眠 3 秒
TimeUnit.SECONDS.sleep(3);
dataOperator.setNum2New(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " num :" + dataOperator.num);
}, "edit num thread").start();
while (dataOperator.num == 0) {
// 阻塞 main 线程
}
System.out.println(Thread.currentThread().getName() + " the num is " + dataOperator.num + " not zero");
}
}
class DataOperator {
volatile int num = 0;
public void setNum2New(int newNum) {
this.num = newNum;
}
public void incrNum() {
num++;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
volatile AtomicInteger atomicInteger2Num = new AtomicInteger();
public void atomicIncrNum() {
atomicInteger2Num.getAndIncrement();
}
}
/**
* VolatileKeywordTest
* <br/>
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/12/29
* @copyright 蛋壳创意科技 - www.dankal.cn
*/
class InstructionRearrangementTest {
public static void main(String[] args) {
// 指令 1
int a = 1;
// 指令 2
int b = 3;
// 指令 3
a += 5;
// 指令 4
b = a + 3;
// 顺序执行
// 1 2 3 4
// 指令重排
// 2 1 3 4
// 1 3 2 4
// 1 2 4 3
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment