创建一个账户类
package com.duanhw.demo22.account;import org.springframework.beans.factory.annotation.Value;//@Service
public class AccountService {@Value("1000")private Integer balance;//存款public void deposit(Integer amount){int newbalance =balance+ amount;try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}balance=newbalance;}//取款public void withdraw(Integer amount){int newbalance =balance - amount;try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}balance=newbalance;}//查询余额public Integer getBalance(){return balance;}
}
创建一个测试类
package com.duanhw.demo22;import com.duanhw.demo22.account.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;@SpringBootTest(classes = AccountServiceTest.class)
public class AccountServiceTest {/*** @Scope("prototype") 每次调用都会创建一个新的实例* @Scope("singleton") 默认值,每次调用都会返回同一个实例* */@Bean@Scope("prototype") //此项不加 无法保证线程安全public AccountService accountService() {return new AccountService();}@Testpublic void test(@Autowired AccountService accountService1, @Autowired AccountService accountService2) {new Thread(() -> {accountService1.deposit(500);}).start();new Thread(() -> {accountService2.withdraw(500);}).start();try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("进程1:"+accountService1.getBalance());System.out.println("进程2:"+accountService2.getBalance());}}
如果不加@Scope(“prototype”)
输出结果为
进程1:1500
进程2:1500
添加@Scope(“prototype”)
输出结果为
进程1:1500
进程2:500