定义一个变量i=1,同时启动四个线程,
其中两个线程对i执行加1操作,
另外两个线程对i执行减1操作,
输出最后i的值
public class Zu{
static int i=1;//变量i=1
public static void main(String[] args) {
for(int j=0;j<2;j++) {
//i++线程
Thread t1=new Thread() {
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
};
//i--线程
Thread t2=new Thread() {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
i--;
}
};
t1.start();
t2.start();
}
while(Thread.activeCount()>1) {}
System.out.println(i);
}
}