Java多线程

2019-11-13 18:18发布

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);
}
}

}
不懂为什么还是执行了九次

标签:
1条回答
劳资没心,怎么记你
2楼-- · 2019-11-13 18:33

你把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);
            }
        }
    }
}
查看更多
登录 后发表回答