新开一个线程事务怎么控制?

在run方法里没法用@Transactional来做事务,run方法上又不能加exception,怎么能控制事务保证异常就回滚呢?

Qyouu
浏览 1163回答 4
4回答

ITMISS

run方法里调service方法。

千巷猫影

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。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java