java – 为什么在线程同步时阻止了WebMethods?

请参阅我的JAX-WS Web服务的代码示例:

@WebService
public class ClassA {

@WebMethod
public synchronized void doSomething() {
    new Thread(new Runnable() { // Thread X
        @Override
        public void run() {
            synchronized (ClassA.this) {
                // Do something which should be run in this separate
                // thread, but not twice at the same time
                try {
                    System.out.println("Thread X Start");
                    Thread.sleep(10000);
                    System.out.println("Thread X End");
                } catch (InterruptedException e) {
                }
            }
        }
    }).start();
}

}

如果WebMethod被调用两次,第二次调用正在等待线程X完成 – 为什么?

最佳答案 问题是你已经同步了doSomething.这肯定会被删除,因为它会阻止您的Web服务中的多线程.对于内部同步块,我也会删除它并尝试使用
single-Thread ThreadPool,以便一次执行一个作业.

    // Initiate you thread pool and make sure it is unique
    ExecutorService service = Executors.newFixedThreadPool(1);

    ...
    // In your web method:
    Future<?> futureResult = service.submit(new Runnable()/or new Callable());
    // Using callable, you will get a Typed Future

    Object result = futureResult.get();// If you need to wait for the result of the runnable/callable.
    ...

这是从Java 1.5开始提供的

点赞