This example will introduce how to get a synchronized Set from TreeSet with synchronizedSet method of Collections class in Java .
Source Code
package com.beginner.examples;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
public class GetSynchronizedTreeSetExamples {
public static void main(String[] args) {
TreeSet tSet = new TreeSet();
// Get a synchronized collection
SortedSet synSet = Collections.synchronizedSortedSet(tSet);
/*
* No errors occur when multiple threads operate on elements in synSet
*/
synSet.add("a");
synSet.add("c");
synSet.add("b");
System.out.println(synSet);
}
}
Output:
[a, b, c]
References
Imported packages in Java documentation: