public class 多线程安全 {
public static void main(String[] args) {
// TODO Auto-generated method stub
thread3 th=new thread3();
Thread T1=new Thread(th);
Thread T2=new Thread(th);
Thread T3=new Thread(th);
T1.start();
T2.start();
T3.start();
}
}
class bank{
private int sum;
public void add(int n) {
sum=sum+n;
System.out.println(sum);
}
}
class thread3 implements Runnable{
private bank b=new bank();
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=3;i>=1;i--) {
b.add(100);
}
}
}
不懂为什么还是执行了九次
你把i放外边,再给run加个类锁,就只运行三次了
class thread3 implements Runnable {
private bank b = new bank();
private int i = 3;
@Override
public void run() {
synchronized (this) {
for (; i >= 1; i--) {
b.add(1);
}
}
}
}
你开启了三个线程,每个线程都去执行thread3的for,而theard3的for循环中的i变量,每次都被重新初始化为3,所以执行9次.
– 森离九 5年前