Java Collections synchronizedNavigableSet()

synchronizedNavigableSet() 用于获取由指定的NavigableSet支持的同步(线程安全)NavigableSet。

1 语法

public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) 

2 参数

s:它是NavigableSet,将被包装在一个同步的NavigableSet中。

3 返回值

返回指定NavigableSet的同步NavigableSet。

4 synchronizedNavigableSet()示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        NavigableSet<String> set = new TreeSet<>();
        set.add("Instagram");
        set.add("Yiidian");
        set.add("Facebook");
        set.add("Google");
        Set<String> synset = Collections.synchronizedNavigableSet(set);
        System.out.println("Synchronized navigable set is :" + synset);
    }
}

输出结果为:

Synchronized navigable set is :[Facebook, Google, Instagram, Yiidian]

5 synchronizedNavigableSet()示例2

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        NavigableSet<Integer> set = new TreeSet<>();
        set.add(1001);
        set.add(1002);
        set.add(1003);
        set.add(1004);
        set.add(1005);
        System.out.println("Set before Synchronized navigable set: " + set);
        Set<Integer> synset = Collections.synchronizedNavigableSet(set);
        set.remove(1004);
        System.out.println("Synchronized navigable set after remove(1004):" + synset);
    }
}

输出结果为:

Set before Synchronized navigable set: [1001, 1002, 1003, 1004, 1005]
Synchronized navigable set after remove(1004):[1001, 1002, 1003, 1005]

6 synchronizedNavigableSet()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedNavigableSet的例子
 */
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(0);
    public static void main(String[] args) throws InterruptedException {
        NavigableSet<Integer> s = new TreeSet<>();
        NavigableSet<Integer> theSet = Collections.synchronizedNavigableSet(s);
        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

 

热门文章

优秀文章