我试图创建各种单例模式,并使用数百万个线程检查中断。我希望这将使我最终实施Bill Pugh。但是我什至无法打破经典。

Singleton:以前尝试过一百万个线程,所有线程都具有相同的哈希码。因此,我将其睡眠了10秒钟,以便确保两个线程都确保输入空检查条件,但都感到沮丧。

package demo2;

public class Singleton {

    private static Singleton soleInstance = null;

    private Singleton() throws InterruptedException {

    }

    public static Singleton getInstance() throws InterruptedException {

        if (soleInstance == null) {

            Thread.sleep(10000);

            soleInstance = new Singleton();

        }

        return soleInstance;

    }

}


测试类别:

package demo2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

class Test {

    public int makeSingleton() throws InterruptedException {

        Singleton s = Singleton.getInstance();

        return s.hashCode();

    }

    public static void main(String[] args) throws InterruptedException, ExecutionException  {

        Test t = new Test();

        ExecutorService executor = Executors.newFixedThreadPool(2);

        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < 2; i++) {

            Future<Integer> future = executor.submit(new Callable<Integer>() {

                public Integer call() throws InterruptedException {

                     return t.makeSingleton();
                }
            });

            list.add(future.get());
        }

        executor.shutdown();

        List<Integer> list2 = list.stream().distinct().collect(Collectors.toList());

        System.out.println(list2);

    }
}


我该怎么打破它?

最佳答案

下面提到的代码将起作用。

更改您的代码。可能是您仅在调用get inside方法而正在等待获取结果,并且循环计数不会增加。

ExecutorService executor = Executors.newFixedThreadPool(2);

        List<Future<Integer>> list = new ArrayList<Future<Integer>>();

        for (int i = 0; i < 5; i++) {

            Future<Integer> future = executor.submit(new Callable<Integer>() {

                public Integer call() throws InterruptedException {

                    return Singleton.getInstance().hashCode();
                }
            });

            list.add(future);
        }

        executor.shutdown();

        Set<Integer> output = new HashSet<Integer>();
        for(Future<Integer> future : list){
            output.add(future.get());
        }

        System.out.println(output);

07-24 09:28