創建一個賬戶類
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