我需要创建一个类来包装其他非“线程安全”的类和方法(第 3 方)。我实际上想创建一个单线程类/方法。
这应该这样做:
public class SomeClass {
    public static synchronized void performTask(int val) {
        //interesting non-thread safe code...
        ThisClass thisclass = new ThisClass();
        thisclass.dostuff();
        ThatClass thatclass = new ThatClass();
        thatclass.dootherstuff();
        HisClass hisclass = new HisClass();
        hisclass.notsure();
    }
1 个静态类和 1 个同步的静态方法。因此,如果多个对象正在使用/调用此类。他们将不得不“排队”等待。如果负载过重,性能会受到影响。
public class MyClass {
    public void mytask() {
        //interesting code
        SomeClass.performTask(myval); // will wait if some other code block is in SomeClass.performTask?
    }