62,628
社区成员
发帖
与我相关
我的任务
分享public class SimpleVolatile1 {
static class BossThread {
public volatile int age = 30;
public void execBirth(){
age++;
System.out.println("boss.age++");
}
public void print(){
while(age < 31) {
System.out.println(age);
}
}
}
public static void main(String[] args){
BossThread bt = new BossThread();
for(int i=0; i<10; i++){
new Thread(bt::print).start();
}
new Thread(bt::execBirth).start();
}
}
30
30
30
30
boss.age++
30
30
30
30
30
30
package com.fr.function;
public class Test {
static class BossThread {
public volatile int age = 30;
public void execBirth(){
age++;
System.out.println("boss.age++");
}
public void print(){
for (int i = 0; i < 10; i++) {
System.out.println(age);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
BossThread bt = new BossThread();
new Thread(bt::print).start();
Thread.sleep(50);
new Thread(bt::execBirth).start();
}
}
你的代码有问题,我改了下。
输出
30
30
30
30
boss.age++
31
31
31
31
31
31