Java Collections synchronizedSet()

synchronizedSet() 用于获取由指定集合支持的同步(线程安全)集合。

1 语法

public static <T> Set<T> synchronizedSet(Set<T> s)  

2 参数

s:该集合将被包装在一个同步集合中。

3 返回值

返回指定集的同步集合。

4 synchronizedSet()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedSet的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create set
        Set<String> set = new HashSet<String>();
        //Add values in the set
        set.add("Facebook");
        set.add("Twitter");
        set.add("Whatsapp");
        set.add("Instagram");
        //Create a synchronized set
        Set<String> synset = Collections.synchronizedSet(set);
        System.out.println("Synchronized set is :"+synset);
    }
}

输出结果为:

Synchronized set is :[Twitter, Instagram, Facebook, Whatsapp]

5 synchronizedSet()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedSet的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        Set<Integer> set = Collections.synchronizedSet(new HashSet<>());
        set.add(101);
        set.add(102);
        set.add(103);
        set.add(104);
        set.add(105);
        System.out.println("Set before Synchronized set: " + set);
        System.out.println("Set after Synchronized set-");
        //Using iterator must be synchronized manually
        synchronized (set) {
            Iterator<Integer> iterator = set.iterator();
            while (iterator.hasNext()) {
                Integer num = iterator.next();
                System.out.println(num);
            }
        }
    }
}

输出结果为:

Set before Synchronized set: [101, 102, 103, 104, 105]
Set after Synchronized set-
101
102
103
104
105

6 synchronizedSet()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedSet的例子
 */
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo {

    private static AtomicInteger atomicInteger = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {
        Set<Integer> s = new HashSet<>();
        Set<Integer> set = Collections.synchronizedSet(s);
        System.out.println("initial set size: " + set.size());
        final ExecutorService e = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            e.execute(() -> set.add(atomicInteger.incrementAndGet()));
        }
        e.shutdown();
        e.awaitTermination(1000, TimeUnit.SECONDS);
        System.out.println(set.size());//should be 1000
    }
}

输出结果为:

initial set size: 0
1000

 

热门文章

优秀文章