当前位置:网站首页>High concurrency day02 (concurrent package)

High concurrency day02 (concurrent package)

2022-07-19 07:27:00 yygyj

Two 、 ConcurrentHashMap---- Concurrent hash mapping
1. The bottom layer is based on arrays + Linked list structure to store data
2. The default initial capacity is 16, The default load factor is 0.75, By default, the time tilt of capacity expansion is doubled each time
hashmap Thread safe but not highly concurrent

3. Just used segmentation ( bucket ) Locking mechanism . In later versions ,ConcurrentHashMap In order to improve efficiency , On the basis of sectional lock , Introduce read-write locking mechanism
a. Read the lock : Allow multiple threads to read , Threads are not allowed to write
b. Write lock : Only one thread is allowed to write , Multiple threads are not allowed

4. stay JDK1.8 in , Introduced CAS(Compare And Swap, Compare and exchange ) Lock free algorithm ensures thread safety
5. from JDK1.8 Start , If the number of elements in a bucket exceeds 8 When it's time , The linked list in this bucket will turn into a red black tree ; If not enough 7 individual , Then the red and black tree turns back to the linked list

6. Red and black trees :
a. Red black tree is essentially a self balanced binary search tree
b. Features of binary search tree :
i. The left subtree is smaller than the root
ii. The right subtree is larger than the root

c. Characteristics of the red black tree :
i. Nodes are not red or black
ii. The root node is a black node
iii. The child nodes of the red node must be black nodes , But the child nodes of the black node are not necessarily
Red node
iv. The bottom leaf node must be a black empty node
v. The number of black nodes in the path from the root node to any leaf node
coincident , That is, the height of the black node is the same
vi. The newly added node must be a red node

d. Red and black tree modification - The premise must be that both parent and child nodes are red – The correction process is a chain process
i. Uncle node is red , Then blacken the parent node and uncle node , Will grandfather node
Paint red
ii. Uncle node is black , And the current node is the right cotyledon , Then take the current node as the axis
To carry on the left-hand

 Insert picture description here
 Insert picture description here
iii. Uncle node is black , And the current node is the left child , Then take the parent node as the axis
Right lateral rotation
 Insert picture description here
 Insert picture description here
Amend the case :
 Insert picture description here
e. The query time complexity of red black tree is o(logn)

3、 ... and 、ConcurrentNavigableMap- Concurrent navigation mapping
1. Provides methods for intercepting submaps
2. Generally, implementation classes are used ConcurrentSkipListMap- Concurrent jump table mapping
3. Skip list :
a. Elements must be ordered
b. Extract the original data to form a jump table , The jump table can be extracted one layer up , But the elements in the top jump table are at least 2 individual , It's usually 2-4 individual
c. Jump table is a typical product of space for time
d. Applicable to multiple queries , Less additions and deletions
e. If you add a new node , Whether this node should be extracted into the hop table of the previous layer , follow " Flip a coin " principle
f. The query time complexity of jump table is o(logn)

ConcurrentNavigableMap<String, Integer> map =
new ConcurrentskipListMap<>();
map.put( "a",3);map.put( "d",3);
map.put( "h",3);map.put( "w",3);
map.put( "j",3);map.put( "o",3);
map.put( "e",3);map.put( "s",3);
system.out.println(map );
system.out.printlh( map.subMap( "d","j"));//d To j
System.out.println(map.headMap( "o"));//
system.out.println(map.tailMap("h"));//h To the end 

ExecutorService - Actuator service
One 、 summary
1. The meaning of thread pool : Reduce the creation and destruction of server-side threads , Reuse threads
2. When creating a thread pool, you need to define a certain number of threads
3. Every time you accept a request, a thread will be created ( Core thread ) To handle this request
4. The core thread will not be destroyed after processing the request, but wait for the next request
5. Before the number of core threads reaches , Each incoming request will create a new core thread
6. If all core threads are occupied , Then subsequent requests will be placed in the work queue .
7. If the work queue is also occupied , Then the thread pool will create a temporary thread to process the request . If the temporary thread finishes executing the task , Survive for a specified period of time , If there is no new task processing within this period of time , Then this temporary thread will be kill fall .

8. If the temporary thread is also occupied , Then the new request will be handed over to
RejectedExecutionHandler - Processor processing denied
9. Requests in the work queue are only handed over to the core thread

package cn.tedu.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceDemo {
    
	public static void main(String[] args) {
    
		// Creating a thread pool 
		// Creating a thread pool 
		// corePoolSize - Number of core threads 
		// maximumPoolSize - Thread pool size = Number of core threads + Number of temporary threads 
		//keepAliveTime -  Lifetime of temporary thread 
		// unit -  Time unit 
		//workQueue - Work queue 
		//handler---- Reject handler 


		ExecutorService es=
				new ThreadPoolExecutor(
						5, //5 Core threads 
						10,//5 Core threads +5 A temporary thread 
						5,TimeUnit.SECONDS, // Temporary threads survive after they are used up 5 second 
						new ArrayBlockingQueue<Runnable>(5),// Work queue  
						new RejectedExecutionHandler() {
    
							
							@Override
							public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    
								
								System.out.println(" Thread execution denied "+r);
							}
						});
		// Commit thread 
		for (int i = 0; i < 23; i++) {
    
			es.execute(new EsRunnable());
		}
		
		// Close thread pool 
		es.shutdown();
				
	}
}

class EsRunnable implements Runnable{
    

	@Override
	public void run() {
    
		System.out.println("hello ~~~~");
		try {
    
			Thread.sleep(5);
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
	}
	
}

 Print the results 
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~
 Thread execution denied cn.tedu.threadpool.EsRunnable@232204a1
hello ~~~~
 Thread execution denied cn.tedu.threadpool.EsRunnable@4aa298b7
 Thread execution denied cn.tedu.threadpool.EsRunnable@7d4991ad
 Thread execution denied cn.tedu.threadpool.EsRunnable@28d93b30
hello ~~~~
 Thread execution denied cn.tedu.threadpool.EsRunnable@1b6d3586
 Thread execution denied cn.tedu.threadpool.EsRunnable@4554617c
 Thread execution denied cn.tedu.threadpool.EsRunnable@74a14482
 Thread execution denied cn.tedu.threadpool.EsRunnable@1540e19d
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~
hello ~~~~

Two 、Callable
1. yes JDK1.5 Provides a thread for concurrency and returning results
2. Callable and Runnable The difference between :
a. Return value : Runnable No return value ,Callable You can define the return value
b. Starting mode : Runnable Can pass Thread Class or thread pool to start , however Callable It can only be started through the thread pool
c. Exception mechanism : Runnable Exception not allowed ,callable Allow exceptions to be thrown , So that means callable If an error is reported, it can be handled in a global way

package cn.tedu.threadpool;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceDemo2 {
    
	public static void main(String[] args) throws Exception, ExecutionException {
    
		// characteristic :
		//1. No core threads , Are temporary threads 
		//2. The number of temporary threads is Integer.MAX_VALUE
		// It can be considered that the number of threads in this thread pool is infinite 
		//3. Temporary threads are allowed to survive after they are used up 1min
		//4. A work queue is a synchronous queue 
		// Large threads, small queues 
		// Use scenarios : High concurrency 、 Short task scenario ( Send a message )
// ExecutorService es=Executors.newCachedThreadPool();
		
		// characteristic :
		//1. No temporary threads , Are core threads 
		//2. The work queue is a blocking chain queue ,
		// The default capacity is Integer.MAX_VALUE
		// It can be thought that unlimited tasks can be stored 
		// Small pool, large queue 
		// Use scenarios : Long task ( There are many Baidu cloud disk download tasks , Downloading is the core thread work ,
		// Waiting for download is stored in the queue )
		ExecutorService es2=Executors.newFixedThreadPool(5);
		// Encapsulate the results into Future object , Generics represent the types of actual results 
		Future<String> f = es2.submit(new CThread());
		
		es2.shutdown();
		System.out.println(f.get());
	}
}

// Generics represent the type of the return value 
// Define generics as Void No return value 
class CThread implements Callable<String>{
    

	@Override
	public String call() throws Exception {
    
		return "SUCESS";
	}
}

3、 ... and 、scheduledExecutorService Timing actuator server
1. Timing effect can be achieved
2. It is the underlying mechanism of many timers

package cn.tedu.threadpool;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class scheduledExecutorServiceDemo {
    
	public static void main(String[] args) {
    
		
		// Create a timed thread pool 
		ScheduledExecutorService ses=
				Executors.newScheduledThreadPool(5);
		
		// Timing execution 
// callable  Thread to execute 
		// delay  The time delayed 
		//unit  Time unit 
		// After the thread pool is started , delay 5s Execute this thread 
// ses.schedule(new ScheduleRunnable(), 5, TimeUnit.SECONDS);
		
		
		//
		//command ---
		//initialDelay
		//period
		//unit
		// every other 5s Do it once 
		// If the thread execution time is less than the interval , Start timing from the beginning of the last execution  ---5s
		// If the thread execution time is greater than the interval , According to the thread time 
// ses.scheduleAtFixedRate(new ScheduleRunnable(), 0, 5, TimeUnit.SECONDS);
		
		
		//
		// Start timing from the end of the last execution -----8s
		ses.scheduleWithFixedDelay(new ScheduleRunnable(), 0, 5, TimeUnit.SECONDS);
	}
}
class ScheduleRunnable implements Runnable{
    

	@Override
	public void run() {
    
		System.out.println("hello ~~~~");
		try {
    
			Thread.sleep(3000);
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
	}
	
}

Four 、ForkJoinPool - Bifurcated coalescence pool
1. Bifurcation : Split a big task into several small tasks and then distribute them on different cores
Merge : Summarize the execution results of the forked threads
2. Forking and merging can effectively improve CPU Utilization ratio
3. More data , The more efficient forking and merging are relative to loops
5. In order to prevent the overall efficiency reduction caused by full tasks , Forking and merging have taken work-stealing ( work
Steal ) Strategy - When the task on a core is completed , This core will not be idle, but to randomly scan a core and then come from the end of the task list of this core “ steal ” A task comes back to perform

package cn.tedu.threadpool;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {
    
	public static void main(String[] args) throws Exception, Exception {
    
		long begin=System.currentTimeMillis();
		// seek 1-100000000000L And 
		long sum=0;
		for (int i = 0; i < 100000000000L; i++) {
    
			sum+=i;
		}
		System.out.println(sum);
		
// ForkJoinPool pool=new ForkJoinPool();
// Future<Long> f = pool.submit(new Sum(1,1000000000L));
// pool.shutdown();
// System.out.println(f.get());
		long end=System.currentTimeMillis();
		System.out.println(" Time consuming "+(end-begin));
	}
}
class Sum extends RecursiveTask<Long>{
    
	
	private long start;
	private long end;
	public Sum(long start, long end) {
    
		super();
		this.start = start;
		this.end = end;
	}
	@Override
	protected Long compute() {
    
		if(end-start<=10000){
    
			long sum=0;
			for (long i = start; i <=end; i++) {
    
				sum+=i;
			}
			return sum;
		}else{
    
			long mid=(start+end)/2;
			Sum left=new Sum(start,mid);
			Sum right=new Sum(mid+1,end);
			
			// Bifurcation 
			left.fork();
			right.fork();
			
			// Merge 
			return left.join()+right.join();
			
		}
	}
	
}

Lock- lock
One 、 summary
1.synchronized In use , You need to pay attention to the lock object . Its use is not flexible
2. Lock It is the top-level interface of lock , So the implementation class is used ReentrantLock
3.ReadWriteLock: Read-write lock .
3.ReadWriteLock: Read-write lock
a. Read the lock : Allow multiple threads to read , But threads are not allowed to write
b. Write lock : Only one thread is allowed to write , But threads are not allowed to read
4. Fair and unfair strategies
a. Unfair strategy : In the case of limited resources , There may be unequal preemption times between threads
b. Fair strategy : In the case of limited resources , Ensure that the number of times each thread executes is basically equal
c. Unfair strategies are more efficient
d. synchronized Unfair strategy
e. Lock Default is also unfair

package cn.tedu.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    
	static int i=0;
	public static void main(String[] args) throws Exception {
    
		Lock lock=new ReentrantLock();
		new Thread(new Add(lock)).start();
		new Thread(new Add(lock)).start();
		Thread.sleep(5000);
		System.out.println(i);
	}
}
class Add implements Runnable{
    
	private Lock  lock;
	public Add(Lock lock) {
    
		this.lock=lock;
	}

	@Override
	public void run() {
    
		// Lock 
		lock.lock();
// synchronized (Add.class) {
    
			for (int i = 0; i < 10000; i++) {
    
				LockDemo.i++;
			}
// }
		
			// Unlock 
			lock.unlock();
	}
	
}

Two 、 Other locks
1.CountDownLatch: atresia / Thread decrement lock . Count threads , When the count returns to zero, release the blocking

shift +alt+ a Column mode

package cn.tedu.lock;

import java.util.concurrent.CountDownLatch;

class CountDownLatchDemo {
    
	public static void main(String[] args) throws Exception {
    
		CountDownLatch cdl=new CountDownLatch(5);
		new Thread(new Teacher(cdl)).start();
		new Thread(new Student(cdl)).start();
		new Thread(new Student(cdl)).start();
		new Thread(new Student(cdl)).start();
		new Thread(new Student(cdl)).start();
		// Get stuck before the count returns to zero 
		cdl.await();
		System.out.println(" The exam begins ^^^");
	}
}
class Teacher implements Runnable{
    
	private CountDownLatch cdl;
	public Teacher(CountDownLatch cdl) {
    
		this.cdl=cdl;
	}

	@Override
	public void run() {
    
		System.out.println(" The invigilator arrived at the examination room ~~~~~");
		// Reduce one count 
		cdl.countDown();
	}
	
}
class Student implements Runnable{
    
	private CountDownLatch cdl;
	public Student(CountDownLatch cdl) {
    
		this.cdl=cdl;
	}
	@Override
	public void run() {
    
		System.out.println(" Candidates arrive at the examination room ~~~");
		// Reduce one count 
		cdl.countDown();
	}
	
}

2.CyclicBarrier: fence . Count threads , When the count returns to zero, release the blocking

 Insert picture description here

package cn.tedu.lock;

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    
	public static void main(String[] args) {
    
		CyclicBarrier cb=new CyclicBarrier(4);
		new Thread(new Runner(cb),"1").start();
		new Thread(new Runner(cb),"2").start();
		new Thread(new Runner(cb),"3").start();
		new Thread(new Runner(cb),"4").start();
	}
}
class Runner implements Runnable{
    
	private CyclicBarrier cb;
	public Runner(CyclicBarrier cb) {
    
		this.cb=cb;
	}

	@Override
	public void run() {
    
		String name=Thread.currentThread().getName();
		try {
    
			Thread.sleep((long)(Math.random()*3000));
			System.out.println(name+" Athlete No. 1 has reached the starting line ~~~~");
			// Let the current thread get blocked , Reduce one count at the same time 
			// When the count returns to zero , Just open the jam 
			cb.await();
			System.out.println(name+" Athlete No. 1 ran out ~~~~");
		} catch (Exception e) {
    
			e.printStackTrace();
		}
		
	}
	
}

3.Exchanger: Switch . Used to exchange information between two threads

package cn.tedu.lock;

import java.util.concurrent.Exchanger;

public class ExchangerDemo {
    
	public static void main(String[] args) {
    
		Exchanger<String> ex=new Exchanger<>();
		new Thread(new Producer(ex)).start();
		new Thread(new Consumer(ex)).start();
	}
}
class Producer implements Runnable{
    
	private Exchanger<String> ex;

	public Producer(Exchanger<String> ex) {
    
		super();
		this.ex = ex;
	}

	@Override
	public void run() {
    
		String info=" goods ";
		// Producers exchange goods for consumers 
		try {
    
			String msg = ex.exchange(info);
			System.out.println(" Producers receive consumer Exchange "+msg);
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
	}
	
}
class Consumer implements Runnable{
    
	private Exchanger<String> ex;

	public Consumer(Exchanger<String> ex) {
    
		super();
		this.ex = ex;
	}

	@Override
	public void run() {
    
		String info=" money ";
		// Consumers exchange money for producers 
		String msg;
		try {
    
			msg = ex.exchange(info);
			System.out.println(" The consumer receives the exchange from the consumer "+msg);
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
		
	}
}

4.Semaphore: Semaphore . Each thread can get a semaphore , When the semaphore is all
After the Ministry is occupied , Later threads will be blocked , Until a semaphore is released , Then the blocked thread can get the semaphore and continue to execute . In development , Use semaphores to limit current .【 scene : The flow of people in the live broadcast room 】

package cn.tedu.lock;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    
	public static void main(String[] args) {
    
		Semaphore s=new Semaphore(5);
		for (int i = 0; i < 8; i++) {
    
			new Thread(new Table(s)).start();
			
		}
	}
}
class Table implements Runnable{
    
	private Semaphore s;

	public Table(Semaphore s) {
    
		super();
		this.s = s;
	}

	@Override
	public void run() {
    
		try {
    
			// Occupy a table , Reduce the semaphore by one 
			// When the semaphore is 0. No table , Later threads are blocked 
			s.acquire();
			System.out.println(" A group of people occupied a table ~~~~");
			Thread.sleep((long)Math.random()*10000);
			// Free a table , Signal plus one 
			System.out.println(" A group of people left , Free a table ");
			s.release();
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
		
	}
	
}

Two 、 Atomic operation
1. This attribute is in the calculation process , Will not be preempted by other threads , Ensure the atomicity of attributes
2. In development , You can use the customary locking mechanism instead

package cn.tedu.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {
    
	// Atomic integer 
	// Locking mechanism for a single attribute 
	static AtomicInteger ai=new AtomicInteger(0);
	public static void main(String[] args) throws Exception {
    
		CountDownLatch cdl=new CountDownLatch(2);
		new Thread(new Add(cdl)).start();
		new Thread(new Add(cdl)).start();
		cdl.await();
		System.out.println(ai);
	}
}
class Add implements Runnable{
    
	private CountDownLatch cdl;
	public Add(CountDownLatch cdl) {
    
	super();
	this.cdl = cdl;
}

	@Override
	public void run() {
    
		for (int i = 0; i < 10000; i++) {
    
			AtomicIntegerDemo.ai.incrementAndGet();
		}
		cdl.countDown();
	}
	
}
原网站

版权声明
本文为[yygyj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170519525246.html