我有一個來自外部API的類,我想創建一個實例並從不同線程訪問該對象的方法。我的問題在以下代碼中註釋:使用外部API對象的java中的線程安全
import java.util.concurrent.Executors;
public class ThreadSafetyQuestion {
static class ExternalAPIObject {
void method(){
}
}
private static volatile ExternalAPIObject obj;
static synchronized ExternalAPIObject syncGetObject(){
return obj;
}
public static void main(String[] args) {
Executors.newSingleThreadExecutor().submit(()-> {
ThreadSafetyQuestion.syncGetObject().method();//Is this thread safe?
ExternalAPIObject externalAPIObject = ThreadSafetyQuestion.syncGetObject();
//do some other stuff
externalAPIObject.method();//I doubt this is thread safe. How can I access this method from multiple threads in a safe way?
});
}
}
所以你說我必須在同步包裝方法中包裝ExternalAPIObject的每個單獨的方法?呃..好的,我會聽取你的建議,並就這個話題進行更多的研究。 – dQw4w9WyXcQ