标签:val 技术 final 线程安全 成员 lda value get end
class Counter{
int count = 0;
public synchronized void add(int n){
count += n;
}
public synchronized void dec(int n){
count -= n;
}
public int get(){//读取一个int类型是原子操作,不需要同步
return count;
}
}
class AddThread extends Thread {
Counter counter;
public AddThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < Main.LOOP; i++) {
counter.add(1);
}
}
}
class DecThread extends Thread{
Counter counter;
public DecThread(Counter counter){
this.counter = counter;
}
public void run(){
for(int i=0;i<Main.LOOP;i++){
counter.dec(1);
}
}
}
public class Main{
static final int LOOP=10000;
public static void main(String[] args) throws InterruptedException{
Counter counter = new Counter();
Thread t1 = new AddThread(counter);
Thread t2 = new DecThread(counter);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.get());
}
}
public int get(){ //读取一个int类型是原子操作,不用同步
return count;
}
public synchronized int[] get(){
int[] result = new int[2];
result[0] = this.value[0];
result[1] = this.value[1];//读取万result[0],如果其他线程改变了result[1]的值,会导致读取的结果不一致。
return result;
}
所以,为了保险起见,读取方法通常也要同步。
如果一个类被设计为允许多线程正确访问:
非线程安全的类:
廖雪峰Java11多线程编程-2线程同步-2synchronized方法
标签:val 技术 final 线程安全 成员 lda value get end
原文地址:https://www.cnblogs.com/csj2018/p/11001483.html