标签:system imp oid logs interrupt ++操作 star read 静态方法
关键字synchronized的作用是实现线程间的同步。它的工作是对同步的代码加锁,使得每一次,只能有一个线程进入同步块,从而保证线程间的安全性。
关键字synchronized可以有多种用法:
下述代码,将synchronized作用于一个给定对象instance,因此每次当线程进入被synchronized包裹的代码段,就都会要求请求instance实例的锁。如果当前有其他线程正持有这把锁,那么新到的线程就必须等待。这样,就保证了每次只能有一个线程执行i++操作。也可以写成备注的形式,两者等价的。
public class AccountingVol implements Runnable {
static AccountingVol instance = new AccountingVol();
static volatile int i = 0;
// public synchronized static void increase(){
// i++;
// }
@Override
public void run() {
// TODO Auto-generated method stub
for(int j = 0;j<10000000;j++){
// increase();
synchronized(instance){
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();t2.start();
t1.join();t2.join();
System.out.println(i);
}
}
标签:system imp oid logs interrupt ++操作 star read 静态方法
原文地址:http://www.cnblogs.com/loogr/p/7296537.html