各位大牛,小弟現在遇到一個問題,就是使用多線程調用一個耗時的方法,如何同步?代碼大體如下:
- final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
- final BusinessService service = new BusinessService();
- for(int i = 0; i < 10; i++)
- {
- scheduler.scheduleWithFixedDelay(new Runnable(){
- @Override
- public void run() {
- service.handleBusiness();
- }
-
- }, i, 5, TimeUnit.MINUTES);
- }
這個時候,如果在handleBusiness()方法上加上
Java代碼:
synchronized
,其它線程就進不了這個方法,因為這個方法需要耗時5分鐘左右,大家幫忙想想有啥好的解決辦法,能讓所有線程不等待,就可以調用這個方法又保持原子操作.
解決方法:handleBusiness()寫成線程安全的就好了。