JAVA 线程安全问题

模拟取钱场景,假设好多个人同时点开手机银行操作 a01 账户 ,而 a01账号实际只有100块.取钱代码不加锁是可能发生安全问题的。

public class Account {
    private String accountId;

    public static Double money = 100.0;


    public Account(String accountId) {

        this.accountId = accountId;

    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

}

实际取钱业务(加锁前) ,判断余额是否够后取钱 

public class AccountService {

    private Account account;

    private String lock_key;


    public AccountService(Account account) {
        this.account = account;
        this.lock_key = account.getAccountId();
    }

    public  void getMoney(Double money){
//         synchronized (lock_key){
             if (money <= Account.money){
                 System.out.println(Thread.currentThread().getName() + "--取钱成功");
                 Account.money = Account.money - money;
                 System.out.println(Thread.currentThread().getName() + "将余额设置为:" + Account.money);
             }
//         }
    }


}

模拟很多个人同时取某个账号的钱

    @Test
    public void threadTest() {
        List<Account> accounts = new ArrayList<>();
        Account account = new Account("a01");
        accounts.add(account);
        Account account1 = new Account("a01");
        accounts.add(account1);
        Account account2 = new Account("a01");
        accounts.add(account2);
        Account account3 = new Account("a01");
        accounts.add(account3);
        Account account4 = new Account("a01");
        accounts.add(account4);
        Account account5 = new Account("a01");
        accounts.add(account5);

        for (int i = 0; i < accounts.size(); i++) {
            AccountService accountService = new AccountService(accounts.get(i));
            new Thread(()->{
                accountService.getMoney(100.0);
            },"Thread-" + i).start();
        }

    }

不加锁的情况下。会发生以下情况。

修改实际业务类 , 使用账户id做锁,避免全部人的操作都受限,相同账号的操作加锁。

public class AccountService {

    private Account account;

    private String lock_key;


    public AccountService(Account account) {
        this.account = account;
        this.lock_key = account.getAccountId();
    }

    public  void getMoney(Double money){
         synchronized (lock_key){
             if (money <= Account.money){
                 System.out.println(Thread.currentThread().getName() + "--取钱成功");
                 Account.money = Account.money - money;
                 System.out.println(Thread.currentThread().getName() + "将余额设置为:" + Account.money);
             }
         }
    }


}

实际测试通过 

 

 

        Callable集合FutureTask实现

这种实现能获取返回值 

public class AccountTest {

    @Test
    public void threadTest() throws ExecutionException, InterruptedException {
        List<Account> accounts = new ArrayList<>();
        Account account = new Account("a01");
        accounts.add(account);
        Account account1 = new Account("a01");
        accounts.add(account1);
        Account account2 = new Account("a01");
        accounts.add(account2);
        Account account3 = new Account("a01");
        accounts.add(account3);
        Account account4 = new Account("a01");
        accounts.add(account4);
        Account account5 = new Account("a01");
        accounts.add(account5);

        for (int i = 0; i < accounts.size(); i++) {
            AccountService accountService = new AccountService(accounts.get(i));
            //实现一个callable任务类
            Callable myCallable = new MyCallable(accountService);
            //丢到FutureTask里面去
            FutureTask futureTask = new FutureTask<>(myCallable);
            //开启线程执行
            Thread thread = new Thread(futureTask, "thread" + i);
            thread.start();
            System.out.println(futureTask.get());
        }

    }

    public class MyCallable implements Callable<String> {

        AccountService accountService;

        public MyCallable(AccountService accountService) {
            this.accountService = accountService;
        }

        @Override
        public String call() throws Exception {
            return this.accountService.getMoney(100.0);
        }
    }

}

手搓线程池

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,// 核心线程数为2,即在没有任务执行时线程池中保持的最小线程数
                5,// 最大线程数为5,即在任务较多时线程池中允许的最大线程数
                60,// 线程空闲时间为60秒,超过这个时间且当前线程数大于核心线程数的线程将被终止
                TimeUnit.SECONDS,// 
                new ArrayBlockingQueue<>(3),// 使用ArrayBlockingQueue作为任务队列,队列容量为3
                Executors.defaultThreadFactory(), // 使用默认的线程工厂创建新线程
                new ThreadPoolExecutor.AbortPolicy() // // 当任务队列已满且线程数达到最大线程数时,新的任务将被拒绝,并抛出RejectedExecutionException异常
        );



        for (int i = 0; i < 9; i++) {
            threadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"正在运行");
                }
            });
        }

这个配置是说常驻线程是2个, 队列最多等待的任务是3个 。

队列里有4个的任务时会启动临时线程。

Queue 里任务个数线程总数(临时线程+常驻线程)
4                        

 2 + 1 个临时线程

5         2  +  2 个临时线程
6         2  + 3  个临时线程
7

 2 + 4 ? 此时超过了允许的总的线程数5

新的任务进来的时候会被直接拒绝放弃

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值