在run方法里没法用@Transactional来做事务,run方法上又不能加exception,怎么能控制事务保证异常就回滚呢?
4 回答
千巷猫影
通过
TA贡献1829条经验 获得超7个赞
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Object> future = executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
// return results
return null;
}
});
// get results
future.get();
通过concurrent
并发编程中的api
可以拿到线程的返回值。
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
final AtomicReference<Object> results = new AtomicReference<>();
Thread t = new Thread() {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
// set results
results.set("success");
condition.signalAll();
lock.unlock();
}
};
t.start();
lock.lock();
condition.await();
// get results
System.out.println(results.get());
lock.unlock();
普通线程也可以使用上述方式模拟线程的返回值,来决定事务的commit/rollback
。
添加回答
举报
0/150
提交
取消