Heim  >  Fragen und Antworten  >  Hauptteil

java - Erstellen Sie eine nicht duplizierte Listensammlung. Was ist an diesem Code falsch?

Die Funktion

hofft, implementiert zu werden, besteht darin, eine solche Funktion für List提供一个原子操作:若没有则添加。因为ArrayList本身不是线程安全的,所以通过集合Collections.synchronizedList将其转换为一个线程安全的类,然后通过一个辅助的方法来为List zu erreichen.

class BadListHelper <E> {  
    public List<E> list = Collections.synchronizedList(new ArrayList<E>());  

    public synchronized boolean putIfAbsent(E x) {  
        boolean absent = !list.contains(x);  
        if (absent)  
            list.add(x);  
        return absent;  
    }  
}  
 

Ist dieser Code thread-unsicher? Wenn ja, können Sie es beweisen? Danke

高洛峰高洛峰2686 Tage vor1090

Antworte allen(2)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:27:37

    ConcurrentSkipListSet不就行了

    Antwort
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:27:37

    不重复的List,不就是个Set?,需要原子,不就是线程安全的Set?

    Antwort
    0
  • StornierenAntwort