public class bankSystem {
static int counter = 1000;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
for (int i = 0; i < 5000; i++) {
decrease(counter);
}
},"t1");
Thread t2 = new Thread(()->{
for (int i = 0; i < 5000; i++) {
increase(counter);
}
},"t2");
t1.start();
t2.start();
t1.join();
t2.join();
log.debug(String.valueOf(counter));
}
public static void decrease(int counter) {
counter--;
}
public static void increase(int counter) {
counter++;
}
}
使用静态方法,对同一个counter进行操作,不会发生上下文切换,而直接在main方法中使用counter++/–,则会大致上下文切换
public class bankSystem {
static int counter = 1000;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
for (int i = 0; i < 5000; i++) {
counter--;
}
},"t1");
Thread t2 = new Thread(()->{
for (int i = 0; i < 5000; i++) {
counter++;
}
},"t2");
t1.start();
t2.start();
t1.join();
t2.join();
log.debug(String.valueOf(counter));
}