我写个全局变量写个AtomicInteger初始化为2,主线程返回不等待,然后开两个线程,每个线程执行时 AtomicInteger减1,在每个线程里面加个if判断,如果AtomicInteger对象为0时,执行某个逻辑。但是有的时候会执行两次,有的时候一次也不执行,该如何修改呢?
这就是线程安全问题吖,可以写一个方法,这个方法加synchronize修饰,然后里面飞业务逻辑是减1,以及当为0时,执行其他逻辑,然后两个线程去调用这个方法。
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest3 {
public static AtomicInteger count = new AtomicInteger(2);
public static void main(String[] args) {
Thread A = new Thread(() -> {
int i = 2;
while (i > 0) {
System.out.println("1A: " + count);
if (count.get() == 0) {
System.out.println("2A: " + count);
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3A: " + count);
count.decrementAndGet();
System.out.println("4A: " + count);
}
i--;
}
});
Thread B = new Thread(() -> {
int i = 2;
while (i > 0) {
System.out.println("1B: " + count);
if (count.get() == 0) {
System.out.println("2B: " + count);
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3B: " + count);
count.decrementAndGet();
System.out.println("4B: " + count);
}
i--;
}
});
System.out.println(count);
A.start();
B.start();
}
}
2
1A: 2
1B: 2
3B: 2
3A: 2
4A: 1
1A: 1
4B: 0
1B: 0
2B: 0
3A: 0
4A: -1
2
1A: 2
1B: 2
3B: 2
3A: 2
4B: 1
4A: 0
1B: 0
1A: 0
2B: 0
2A: 0
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest3 {
public static AtomicInteger count = new AtomicInteger(2);
public static void main(String[] args) {
Semaphore sem = new Semaphore(1);
Thread A = new Thread(() -> {
int i = 2;
while (i > 0) {
try {
sem.acquire();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("1A: " + count);
if (count.get() == 0) {
System.out.println("2A: " + count);
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3A: " + count);
count.decrementAndGet();
System.out.println("4A: " + count);
}
i--;
sem.release();
}
});
Thread B = new Thread(() -> {
int i = 2;
while (i > 0) {
try {
sem.acquire();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("1B: " + count);
if (count.get() == 0) {
System.out.println("2B: " + count);
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3B: " + count);
count.decrementAndGet();
System.out.println("4B: " + count);
}
i--;
sem.release();
}
});
System.out.println(count);
A.start();
B.start();
}
}
2
1A: 2
3A: 2
4A: 1
1A: 1
3A: 1
4A: 0
1B: 0
2B: 0
1B: 0
2B: 0
2
1B: 2
3B: 2
4B: 1
1B: 1
3B: 1
4B: 0
1A: 0
2A: 0
1A: 0
2A: 0