线程同步
在 多个线程 的情况下,对 同一个变量 的 实例变量 进行操作,会引起线程同步问题。
例如:
public class Account {
private double money=3000;
public void getMoney(String name,double money){
if(money
this.money=this.money - money;
System.out.println(name+" 取款 "+money +"元");
}else{
System.out.println("余额不足");
}
}
}
public class T1 extends Thread{
private Account account;
public T1(Account account){
this.account=account;
}
@Override
public void run() {
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.getMoney("Tom", 2000);
}
}
public class T2 extends Thread{
private Account account;
public T2(Account account){
this.account=account;
}
@Override
public void run() {
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.getMoney("Rose", 2000);
}
}
public class AccountTest {
public static void main(String[] args) {
Account a= new Account();
T1 t1=new T1(a);
T2 t2=new T2(a);
t1.start();
t2.start();
}
}
在这种情况下,就可能会出现这种情况:“Tom取款2000元。Rose取款2000元。”即线程不同步。
解决方法
1.同步方法
使用sychronized关键字。 相应代码改为:public sychronized void getMoney(String name,double money){....}
2.同步代码块
使用sychronized(this){ 要同步的代码块} 小括号里面内容不固定。
3.同步锁
使用ReentrantLock类 相应代码改为:
public class Account {
private double money=3000;
private ReentrantLock reentrantLock = new ReentrantLock();
public void getMoney(String name,double money){
ireentrantLock.lock();
try {
if(money < this.money) {
this.money = this.money - money;
System.out.println(name+ "取款" + money + "元");
} else {
System.out.println(name + "余额不足");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
}
以上三种方法能实现线程同步,其中最多时用的是第二种方法同步代码块。