Spring的事务管理多线程的困惑

时间:2025-03-01 12:53:06
  • package ;  
  •   
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  •   
  • @Service("userService")  
  • public class UserService extends BaseService {  
  •     @Autowired  
  •     private JdbcTemplate jdbcTemplate;  
  •   
  •     @Autowired  
  •     private ScoreService scoreService;  
  •   
  •     public void logon(String userName) {  
  •         ("before  method...");  
  •         updateLastLogonTime(userName);  
  •         ("after  method...");  
  •   
  •         //(userName, 20);//①在同一线程中调用scoreService#addScore()  
  •           
  •         //②在一个新线程中执行scoreService#addScore()  
  •         Thread myThread = new MyThread(this.scoreService, userName, 20);//使用一个新线程运行  
  •         ();  
  •     }  
  •   
  •     public void updateLastLogonTime(String userName) {  
  •         String sql = "UPDATE t_user u SET u.last_logon_time = ? WHERE user_name =?";  
  •         (sql, (), userName);  
  •     }  
  •       
  •     //③负责执行scoreService#addScore()的线程类  
  •     private class MyThread extends Thread {  
  •         private ScoreService scoreService;  
  •         private String userName;  
  •         private int toAdd;  
  •         private MyThread(ScoreService scoreService, String userName, int toAdd) {  
  •             this.scoreService = scoreService;  
  •             this.userName = userName;  
  •             this.toAdd = toAdd;  
  •         }  
  •   
  •         public void run() {  
  •             try {  
  •                 (2000);  
  •             } catch (InterruptedException e) {  
  •                 ();  
  •             }  
  •             ("before  method...");  
  •             (userName, toAdd);  
  •             ("after  method...");  
  •         }  
  •     }  
  • }