Java教程

Java Collections syncedSet()

Java集合类的 synchronizedSet()方法用于获取支持的同步(线程安全)集

语法

以下是 synchronizedSet()方法的声明:
public static <T> Set<T> synchronizedSet(Set<T> s)

参数

参数 说明 必需/可选
s 它将被包装在一个同步的集合中。 必需

返回

synchronizedSet()方法返回指定Set的同步视图。

异常

不适用

示例1

import java.util.*;
public class CollectionsSynchronizedSetExample1 {
    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]

示例2

import java.util.*;
public class CollectionsSynchronizedSetExample2 {
    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

示例3

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 CollectionsSynchronizedSetExample3 {
    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

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4