62,614
社区成员
发帖
与我相关
我的任务
分享
static boolean b = true;
public static void task() {
if (b) {
b = false;
System.out.println(Thread.currentThread().getName() + "执行了task");
}
}
public static void main(String[] args) {
Test test = new Test();
for (int i = 0; i < 10; i++) {
new Thread(()-> {
for (int j = 0; j < 10; j++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.task();
}
},"A"+i).start();
}
while (Thread.activeCount() > 2){
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+"方法执行次数"+test.get());
}
}
class Test{
static volatile boolean b = true;
AtomicInteger atomicInteger = new AtomicInteger();
public void task() {
add();
//System.out.println(Thread.currentThread().getName()+"\t 进入方法...");
if (b) {
b = false;
System.out.println(Thread.currentThread().getName() + "修改了值");
}
}
public void add(){
atomicInteger.getAndIncrement();
}
public int get(){
return atomicInteger.get();
}