22 July 2016

Đồng bộ hóa Collections.Synchronization trong Java

Collections.synchronizedXXX(collection)
XXX - List, Map, Set, SortedMap and SortedSet
Collections.Synchronization
Java 2016
List<String> safeList = Collections.synchronizedList(new ArrayList<>());
// adds some elements to the list
Iterator<String> iterator = safeList.iterator();
while (iterator.hasNext()) {
    String next = iterator.next();
    System.out.println(next);
}
Synchronized(nameXXX)
 Java 2016
synchronized (safeList) {
    while (iterator.hasNext()) {
        String next = iterator.next();
        System.out.println(next);
    }
}
package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] args) {
   // create map
   Map<String,String> map = new HashMap<String,String>();
      
   // populate the map
   map.put("1","TP"); 
   map.put("2","IS");
   map.put("3","BEST");
      
   // create a synchronized map
   Map<String,String> synmap = Collections.synchronizedMap(map);
     
   System.out.println("Synchronized map is :"+synmap);
   }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang