Some Java and contracting

Synchronization containers

Vector and ArayList :

        List ArrayList is the most common implementation class, the interior is achieved through an array of elements that allows for fast random access. The disadvantage is that the array can not have a space between each element when the array size does not satisfy the need to increase storage capacity, it is necessary to speak has been copied to the new array of data storage space. When inserting or deleting an element from the intermediate position of ArrayList, the array is required to copy, move, the cost is relatively high. Therefore, it is suitable for random search and traversal, not suitable for insertion and deletion.

        Vector and ArrayList, as is achieved by an array, except that it supports synchronous threads that only one thread at a time can write Vector, avoid multi-threading while writing the inconsistency caused, but synchronization requires a very high cost Therefore, it is slower than access access ArrayList. Vector and ArrayList expansion is not the same, Vector is the default expansion to double the capacity, Arraylist 50% capacity increase

Note: Vector thread-safe, ArrayList

Vector.add Source:

                      

ArrayList.add Source:

                 

Thus, it is seen, Vectory method uses synchronized synchronization function methods written thread synchronization.

HashMap和HashTable:

1.HashMap not thread-safe, HastMap sub-interface is an interface map interface, the object is mapped to a key value, wherein the keys and values ​​are objects, and can not contain duplicate keys, but may contain a duplicate value. HashMap allows null key and null value, and hashtable is not allowed.

2.HashTable Collection is a thread-safe.

3.HashMap Hashtable is lightweight realization (non-thread-safe implementation), they have completed the Map interface, the main difference is that HashMap allows null (null) key (key), due to the non-thread-safe, efficiency may be higher than Hashtable.
HashMap allows null as a key entry or the value, and not allowed Hashtable.
HashMap Hashtable contains methods removed, replaced containsvalue containsKey.

Note: HashTable thread-safe, HashMap thread-safe. The method put the HashTable source also synchronized using synchronization method implemented

synchronizedMap

      Source code using synchronized block, the thread-safe collection amount becomes thread-safe collection

      Example: Collections.synchronizedMap (HashMap), will become HashMap thread synchronization

ConcurrentHashMap

      Under ConcurrentMap interface has two important realization:

  1. ConcurrentHashMap
  2. ConcurrentskipListMap (supports concurrent sorting. Make up ConcurrentHas hMa p)

      ConcurrentHashMap internal use segment (Segment) to represent these different sections, each section is actually a small HashTable, they have their own locks. As long as multiple modifications occur at different segments, they can be complicated. The whole is divided into a 16 segment (Segment. I.e. up to 16 concurrent threads modifying operation. This is also the scene heavy thread lock granularity is reduced thereby reducing lock contention of a solution. Most of the code and the shared variables use the volatile keyword statement, the purpose is the first time access to content modification, the performance is very good. (after java8, abandoned the concept of Segment, instead using CAS algorithm )

ConcurrentHashMap method is obviously due to the efficiency synchronizedMap of

 

CountDownLatch

       CountDownLatch class java.util.concurrent located under the package, which may be implemented using functionally similar counter. For example, there is a task A, it waits for the other to perform after the completion of four tasks to perform, then you can use this function to achieve the CountDownLatch.

public  class test002 { 

    public  static  void main (String [] args) throws InterruptedException { 
        System.out.println ( "child thread is finished wait ..." ); 
        a CountDownLatch CountDownLatch = new new a CountDownLatch (2 );
         new new the Thread ( new new the Runnable ( ) { 

            @Override 
            public  void RUN () { 
                System.out.println ( . "child thread," + Thread.currentThread () getName ( ) + " started ..." ); 
                countDownLatch.countDown (); // each minus 1 times
                System.out.println ( "child thread," + Thread.currentThread () getName ( ) + " end of the execution ...." ); 
            } 
        .}) Start (); 
        new new the Thread ( new new the Runnable () { 

            @Override 
            public  void RUN () { 
                System.out.println ( . "child thread," + Thread.currentThread () getName ( ) + " begin ..." ); 
                countDownLatch.countDown (); 
                System.out.println ( "sub thread, ". + Thread.currentThread () getName () +" end of execution ... " ); 
            } 
        }) Start ();. 

        CountDownLatch.await (); // that called the current method of blocking the main thread countDown result is 0,Blocking becomes operational status
        System.out.println ( "two sub-thread execution completion ...." ); 
        System.out.println ( "main thread continues execution .." ); 
    } 

}

 

CyclicBarrier

The provisions of a number of initialization CyclicBarrier, and then calculate the call CyclicBarrier.await () to enter the number of threads waiting. When the number of threads reached this number, all the threads into a wait state wakes up and continues. 

 CyclicBarrier as its name means, as can be seen as an obstacle, after all threads have gotten together to pass this obstacle together. 

CyclicBarrier also with a parameter of the initial Runnable, this Runnable task after CyclicBarrier number is reached, all other threads to be executed before being awakened.

class Writer extends Thread {
    private CyclicBarrier cyclicBarrier;
    public Writer(CyclicBarrier cyclicBarrier){
         this.cyclicBarrier=cyclicBarrier;
    }
    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + ",正在写入数据");
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            // TODO: handle exception
        }
        System.out.println("Thread" + Thread.currentThread () getName () + ", the write data is successfully ......" ); 
        
        The try { 
            CyclicBarrier.await (); 
        } the catch (Exception E) { 
        } 
        System.out.println ( "All the threads is finished .........." ); 
    } 

} 

public  class test001 { 

    public  static  void main (String [] args) { 
        a CyclicBarrier CyclicBarrier = new new a CyclicBarrier (. 5 );
         for ( int I = 0 ; I <. 5; I ++ ) { 
            Writer Writer = new new Writer(cyclicBarrier);
            writer.start();
        }
    }

}

 

Semaphore

Semaphore is a counting semaphore based. It can set a threshold value, based on this, the signal multiple threads compete to obtain a license to do after their application for restitution, after exceeding the threshold value, the thread will apply for permission signal is blocked. Semaphore objects can be used to construct some of the pool, the pool of resources and the like, such as a database connection pool, we can create a count of the Semaphore. 1, as a mechanism similar to the mutex, the amount of which is also called binary flag indicating two mutually exclusive states. It is used as follows:

availablePermits function to retrieve the number of resources currently available

wc.acquire (); // application resources

wc.release (); // release resources

Example:

        A toilet only three pit-bit, but there are 10 people to the toilet, how to do? Suppose the number of people 10 to 10, respectively, and the toilet No. 1 First, 10 and finally to the toilet. Then came the inevitable 1-3 available pit-bit, well go to the toilet, No. 4 came in front of three people need to see if anyone out, if someone out, in, or wait. By the same token, No. 4-10 are also waiting for the toilet of people came out to go in, and who should go in it depends on whether the person has to wait for quality, whether it can comply with the rules on the first-come first. (turn)

public  class SemaphoreTest {
     public  static  void main (String [] args) throws InterruptedException { 


     / *    // represent up to support the number of resource access, 
        Semaphore semaphore = new new Semaphore (3); 
        // application resources 
        wc.acquire (); 
        // releasing resources 
        semaphore.release (); * / 
        semaphore semaphore = new new semaphore (. 3 );
      for ( int I = 0; I <= 10; I ++ ) {
          new new Prarent (semaphore, "second" + i + "th" ) .start (); 
     } 
    } 
} 

class Prarentthe extends the Thread { 

   Semaphore WC; 
   String name; 

    public Prarent (Semaphore WC, String name) {
         the this .wc = WC;
         the this .name = name; 
    } 

    @Override 
    public  void RUN () {
         // After obtaining the resource, immediately minus one , such as 5-1, instead of wc.acquire (); 
       int A = wc.availablePermits ();
        IF (A> 0 ) { 
           System.out.println (name + "there pit" ); 
       } the else { 
           the System.out .println (name + "no pit" ); 
       } 
        the try{ 
            Wc.acquire (); 
            System.out.println (name + "get pit" ); 
            the Thread.sleep ( new new the Random () the nextInt (1000. )); 
            System.out.println (name "over the" + ); 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } the finally {
             // release resources 
            wc.release (); 
        } 
    } 
}

 

 

Guess you like

Origin www.cnblogs.com/QSC-AcStu/p/11330438.html