技术:java8内存模型 demo
运行环境:IDEA 15.2 + jdk8 + windows 7
demo功能:提供一个使用 volatile关键字的代码demo
volatile线程安全demo:http://demoworld.tech/c/java_volatile_muti_thread_demo
private static boolean flag1 = false;
//当变量没有使用volatile修饰时, 其他线程对变量的值进行修改, 这个线程看不到修改后的值。 很多情况我们是希望其他线程也可以看到
@Test
public void testAccessableForAllThreads1() throws InterruptedException {
new Thread() {
int i = 0;
@Override
public void run() {
while (!flag1) {
i++;
i--;
}
//如果这个线程可以看到flag2被其他线程修改后的值,
// 就会跳出while, 执行下面的语句。 这个测试用例不会执行
System.out.println("i can see other threads change flag's value using volatile varables");
}
}.start();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(2000);
flag1 = true;
System.out.println("i changed flag's value to true, can any thread see it?");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
System.out.println("wait all thrads over...");
Thread.sleep(99999);
}
private static volatile boolean flag2 = false;
//当变量使用volatile修饰时, 其他线程对变量的值进行修改, 这个线程可以看到修改后的值。 符合我们的预期
@Test
public void testAccessableForAllThreads2() throws InterruptedException {
new Thread() {
int i = 0;
@Override
public void run() {
while (!flag2) {
i++;
i--;
}
//如果这个线程可以看到flag2被其他线程修改后的值,
// 就会跳出while, 执行下面的语句。 这个测试用例会执行的。 符合我们的预期
System.out.println("i can see other threads change flag's value using volatile varables");
}
}.start();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(2000);
flag2 = true;
System.out.println("i changed flag's value to true, can any thread see it?");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
System.out.println("wait all thrads over...");
Thread.sleep(99999);
}
欢迎添加微信,互相学习↑↑↑ -_-
白老虎
programming is not only to solve problems, ways to think
grafana 级连 菜单 templating (variables) 配置
rocketmq 集群搭建 (2master + 2slave + 2namesrv)
AI 机器人 抓取 微信 聊天中的 百度网盘 分享地址和密码