在多线程编程环境下,对于共享资源(比如多线程共享的变量)的写操作时,不同线程之间假如没有相互同步,而是随机读取、更改变量回写到内存中,就会出现混乱和错误!因此必须要在多线程的操作方法上添加锁对象,当一个线程进入操作的时候,其它线程必须要等待,这样依次串行完成任务。
synchronized关键字可以将对象或者方法标记为同步,以实现对对象和方法的互斥访问,可以用synchronized(对象) { … }定义同步代码块,或者在声明方法时将synchronized作为方法的修饰符。
下面以银行存钱的例子来说明多线程同步的用途。多个线程往一个账号存钱的问题!
public class Account {
private double balance;
public synchronized void deposit(double money){
double newBalance = balance + money;
try{
Thread.sleep(10);//模拟耗时任务,让其它线程有机会执行
}catch (Exception e){
e.printStackTrace();
}
balance = newBalance;
//System.out.println("now balance = "+balance);
}
public double getBalance(){
return balance;
}
}
public class addMoneyThread implements Runnable {
private Account account;
private double money;
public addMoneyThread(Account account,double money){
this.account = account;
this.money = money;
}
@Override
public void run(){
account.deposit(money);
}
}
测试代码:
public class TestMultThread {
public static void main(String args[]){
Account account = new Account();
ExecutorService executorService = Executors.newFixedThreadPool(100);
for(int i=0; i< 100; i++){
executorService.execute(new addMoneyThread(account,1));
}
executorService.shutdown();
while (!executorService.isTerminated());
System.out.println("balance = " + account.getBalance());
}
}
但是在在存款方法上加了synchronized ,多线程就有顺序了,结果就是100。