Java教程

Java Collections SynchronizedSortedSet()

Java集合类的 synchronizedSortedSet()方法用于获取同步(线程安全的)排序集,由指定的排序集支持。

语法

下面是 synchronizedSortedSet()方法的声明:
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)

参数

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

返回

syncnedSortedSet()方法返回指定排序集的同步视图。

异常

NA

示例1

import java.util.*;
public class CollectionsSynchronizedSortedSetExample1 {
    public static void main(String[] args) {
        //Create set
          SortedSet<String> set = new TreeSet<String>();
          //Add values in the set
          set.add("Facebook");
          set.add("Twitter");
          set.add("Whatsapp");
          set.add("Instagram");
          //Create a synchronized sorted set
          Set<String> synset = Collections.synchronizedSortedSet(set);
          System.out.println("Synchronized Sorted set is :"+synset);
        }
}
输出:
Synchronized Sorted set is :[Facebook, Instagram, Twitter, Whatsapp]

示例2

import java.util.*;
public class CollectionsSynchronizedSortedSetExample2 {
    public static void main(String[] args) {
        SortedSet<Integer> set = Collections.synchronizedSortedSet(new TreeSet<>());
        set.add(101);
        set.add(104);
        set.add(103);
        set.add(102);
        set.add(105);     
        System.out.println("Set after synchronized sorted 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 after synchronized sorted 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 CollectionsSynchronizedSortedSetExample3 {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        SortedSet<Integer> set = new TreeSet<>();
        SortedSet<Integer> theSet = Collections.synchronizedSortedSet(set);
        final ExecutorService e = Executors.newFixedThreadPool(1000);
        for (int i = 1; i <= 1000; i++) {
            e.execute(() -> {
                int n = atomicInteger.incrementAndGet();
                try {
                    theSet.add(n);
                } catch (Exception e1) {
                    System.out.println(e1 + " " + n);
                }
            });
        }
        e.shutdown();
        e.awaitTermination(1000, TimeUnit.SECONDS);
        System.out.println(theSet.size());//should be 1000
    }
}
输出:
1000

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