Concurrent programming - collection

Ordinary collection

List \ Set \ Map, concurrent environment, the process does not allow traversal update operations (additions and deletions)

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CollectionDemo {
    public static void main(String[] args) {
        List<User> list=new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            User user = new User(i, "User" + i);
            list.add(user);
        }
        //java.util.ConcurrentModificationException
//        Iterator<User> it=list.iterator();
//         the while (it.hasNext ()) {
 //             the User User it.next = ();
 //             IF ( "User6" .equals (user.getName ()))
 //                 list.remove (User);
 //         } 

        for ( int I = 0; I <20 is; I ++ ) {
             IF (I% 2 == 0 ) { 
                the User User = (the User) List.get (I);
 //                     every remove elements, the latter will forward one position 3 becomes 2, confusion 
                list.remove (User); 
            } 
        } 
        System.err.println (List); 
    } 
}

Concurrent collections

Nonblocking set ( Non-Blocking Collection ) ConcurrentLinkedDeque

This collection also includes a method of removing and adding data. If the method can not be executed immediately, it returns null or throws an exception, but this method is not the calling thread is blocked.

Examples

Add a large amount of data to a list;

Remove large amounts of data from the same list.

 

import java.util.concurrent.ConcurrentLinkedDeque;

public class CollectionDemo01 {
    public static void main(String[] args) throws InterruptedException{
        ConcurrentLinkedDeque<String> list=new ConcurrentLinkedDeque();
        //添加数据
        Thread[] add=new Thread[100];
        for (int i = 0; i < 100; i++) {
            add[i]=new Thread(()->{
                for (int j = 0; j < 10000; j++) {
                    list.add(Thread.currentThread().getName()+":Element "+j);
                }
            });
            add[i].start();
            add[i].join();
        }
        System.out.println("after add size:"+list.size());

        //移除数据

        Thread[] poll=new Thread[100];
        for (int i = 0; i < 100; i++) {
            poll[i]=new Thread(()->{
                for (int j = 0; j < 5000; j++) {
                    list.pollLast();
                    list.pollFirst();
                }
            });
            poll[i].start();
            poll[i].join();
        }
        System.out.println("after poll size:"+list.size());
    }
}

Blocking collection (Blocking Collection) LinkedBlockingDeque

Blocking set (Blocking Collection): set comprises adding and removing such data. When the collection is full or empty, is called the add or remove methods can not be executed immediately, then call this method the thread will be blocked until the method can be successfully executed.

 

import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

public class BlockDequeDemo {
    public static void main(String[] args) {
        LinkedBlockingDeque<String> list=new LinkedBlockingDeque(3);
        Thread thread=new Thread(()->{
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 5; j++) {
                    String str=new String(i+":"+j);
                    try {
                        list.put(str.toString());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("client:"+str+(new Date()));
                }
            }
        });
        thread.start();

        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 3; j++) {
                try {
                    String str=list.take();
                    System.out.println("main:take "+str+" size:"+list.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println("end");

    }
}

 

import com.sun.javafx.animation.TickCalculation;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class CarDemo {
    public static void main(String[] args) {
        //创建Semaphore
        Semaphore sp=new Semaphore(5);

        Thread[] car=new Thread[10];
        for (int i = 0; i < 10; i++) {
            car[i]=new Thread(()->{
                 // request permission 
                the try { 
                    sp.acquire (); 
                    System.out.println (Thread.currentThread () getName (). + "Can enter the parking lot" ); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace (); 
                } 

                // resources 
                the try {
                     int Val = new new the Random () the nextInt (10. ); 
                    TimeUnit.SECONDS.sleep (Val); 
                    . System.out.println (Thread.currentThread () getName () + "stay" + val + "s" ); 
                } the catch(InterruptedException E) { 
                    e.printStackTrace (); 
                } 
                // away (resource release) 

                the try { 

                    sp.release (); 
                    System.out.println (. Thread.currentThread () getName () + "leave the parking lot" ); 
                } the catch (Exception E) { 
                    e.printStackTrace (); 
                } 
            }, "CAR [" + I + "]" ); 
            CAR [I] .start (); 
        } 


    } 
}

 

 

ArrayBlockingQueue 
ConcurrentHashMap 
ConcurrentLinkedQueue 
ConcurrentSkipListMap 
ConcurrentSkipListSet 
CopyOnWriteArrayList 
CopyOnWriteArraySet

Guess you like

Origin www.cnblogs.com/yintingting/p/11428575.html