多线程|加锁操作

发布时间 2023-08-24 17:15:50作者: 司丝思

class Counter{
public int count = 0;
public void add(){
count ++;
}
}
public class synDemo {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for(int i = 0;i < 10000;i++){
counter.add();
}
});
Thread t2 = new Thread(() -> {
for(int i = 0;i < 10000;i++){
counter.add();
}
});
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(counter.count);
}
}