今天有人给我出了个题目,就是上面的题目,关于银行存钱的事情,问我能不能用简单的方式解决,不要使用队列。
经过一番测试,真的是漏洞百出,首先,真的是应该先明白需求,不然没法往下弄。
我们一起分析下:1.一个账户,两个储户,意味着,两个人需要共享一个变量,往同一个变量里面写入 2.分别存3千,每人存3次,意味着,要给每个人都有3次机会
,你就得想办法判断,当前这个人用了几次还剩几次。如果超过次数,就不允许再存了。那么,你怎么能给每个人都有3次呢??
public class MyThread implements Runnable{
private static int money = 0;
ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
int times = 3;
return times;
}
};
首先,定义一个变量money,也就是账户了。然后用ThreadLocal给每个人分配3次机会。
@SuppressWarnings("static-access")
public int account(int cun){
System.out.println("当前余额为:" + money);
synchronized(this){
Integer times = threadLocal.get();
if(times>0){
times--;
money += cun;
System.out.println(Thread.currentThread().getName() + "来存钱了,存了1000,账户余额=>" + money);
}else{
System.out.println(Thread.currentThread().getName() + "已经存3次了");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return money;
}
threadLocal.set(times);
}
return money;
}
然后threadLocal.get()方法来获取当前这个线程的所剩次数,如果大于零,说明没超过3次,让他继续存,否则,就让该线程休息,放弃当前锁,去切换另一个线程。
@Override
public void run() {
while (true) {
account(1000);
}
}
public static void main(String[] args) throws Exception {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
Thread thread1 = new Thread(myThread1);
Thread thread2 = new Thread(myThread2);
thread1.start();
thread1.sleep(2000);
thread2.start();
thread2.sleep(2000);
}
}
注意看:线程1和线程2分别都睡眠了两秒,为什么这么做呢?目的是让线程排队,线程1忙完了,然后再让线程2去忙。
看看打印结果:
至此,目的已经达到了,谢谢大家的浏览,请继续支持。