一、银行取钱问题?
示例:一个账户拥有10000元,有两个用户同时进行取款,每次取100元,直到取完为止,采用两个线程同时取款。代码如下(示例):
package ThreadsynchronizedPack;
public class HomeWork2 {
public static void main(String[] args) {
Count2 count2 = new Count2();
Thread thread1 = new Thread(count2);
Thread thread2 = new Thread(count2);
thread1.start();
thread2.start();
}
}
class Count1 extends Thread{
@Override
public void run() {
}
}
class Count2 implements Runnable{
int allMoney = 10000;
public void DecreaseMoney(){
synchronized (this){
while (true){
if (allMoney<=0){
break;
}
allMoney-=10;
System.out.println(allMoney+" "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
DecreaseMoney();
}
}
总结
在这里我们应该使用synchronize锁对线程进行同步,防止出现错误。
在使用synchronize锁时需要注意:
synchronized (this) this指的是同一对象,也可以用其他代替(object)(Object object = new Object())
当锁的是static代码块时,这时候synchronize(xxx.class)括号中的对象应该是这个类 xxx.class