synchronized修饰方法,在spring管理的bean中表现同样是获取当前对象的锁。
通过controller调用thread1(),再发起另一个请求调用thread2()。
等待thread1()执行完,才执行thread2()方法。
@Service
public class ThreadSafeServiceImpl implements ThreadSafeService {
@Override
public synchronized Result thread1() {
try {
Thread.sleep(8000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 done");
return null;
}
@Override
public synchronized Result thread2() {
System.out.println("thread2 done");
return null;
}
}
public interface ThreadSafeService {
Result thread1();
Result thread2();
}
thread1 done
thread2 done