Java concurrent programming needs to pay attention to

The yield method means that the current thread is changed from the execution state (running state) to the executable state (ready state). The CPU will choose from many executable states, that is to say, the current thread just now may still be executed again. It does not mean that other threads will be executed and the thread will not be executed next time. .

In the case of multithreading, in the case of shared variables, in order to maintain the consistency of the data, you can use the synchronized keyword, you can add a method, which means that this object is locked, but the efficiency is not high, you can use synchronized code Segment, only lock the shared variable, and if the shared variable is a number, modify the variable with the Atomic keyword. You can not use synchronized. This object is a class provided to me by java concurrent package, which contains addition and subtraction operations

The volatile keyword , the CPU is cached, when the value of the variable has changed, but the CPU will still get an error from the cache value, the volatile keyword is to tell the CPU that the value must be taken from the memory, without leaving the cache, volatile can be achieved Visibility, atomicity cannot be achieved.
Can not solve the concurrency problem. Synchronize can realize the visibility and atomicity problems. Can solve concurrency problems

The role of ThreadLocal is to bind to the current thread. This object has a get and set method, which can put the object into it, and there will be no situation where multiple threads compete for shared variables.

Synchronization container: vector hashtable Collections.synchronize () These are some old APIs, and the source code is basically implemented using synchronization, which is very bulky.

** Concurrent container: ** ConcurrentHashMap segment lock api provided by java 1.5
ConcurrentHashMap map = new ConcurrentHashMap ();
map .putIfAbsent (1,2) This method is to put in if the key does not exist, return none if it exists.

CopyOnWriteArrayList / Set The basic principle of these two implementations is to first lock a lock during operation, then copy a shared resource, and then engage in the copied resource. The scenario used is to read more and write less operating

BlocakingQueue blocking queue. There are two methods, one put to put things, take to take things queue is characterized by first-in first-out, like a water pipe, stuffing things inside. Advanced must come first.

Locked fence semaphore

Blocking means that when the threads are all executed, they are released, how to achieve it? CountDownLatch countdown means

CountDownLatch  latch = new  CountDownLatch (2);   //表示有两个线程

latch.countDown()      //一般线程执行完之后调用这个方法,表示这个线程执行完了

latch.awit()          //这个方法必须是latch里面的线程都执行完了,才放行。

Fence is equivalent to a dam, that is, after a thread reaches a certain state, then this thread can continue to operate

CyclicBarrier barrier = new CyclicBarrier (4)

barrier.await()   //只有当wait的线程等于4,才会继续往下走。不然都得等着。

When the number of semaphores is not equal to the number of producers and consumers, such as 5 machines, 8 people need to use it, at first one for each person, then someone releases it, and another worker makes up.

int t=8  //8个工人
Semaphore semaphore = new  Semaphore(5) //机器的数目

semaphore.acquire();   //意思是从5台机器中获取一个

semaphore.release();    //意思是机器释放,下一个工人就顶上。

Thread Pool

When you encounter concurrency, you must use the thread pool, because you cannot create a thread without a request, then your server will not be able to bear it.

Executor executor = Executors.newFixedThreadPool(100);//意思是这个线程池有100个线程

executor.execute(线程)  //把线程扔进去,就可以了。他就执行线程的start方法。

Executor的实现类ExecutorService   这个类是Executor的实现类,里面有几个非常常用的方法。

Scheduled tasks

The Timer class provided by java can implement timed tasks.
Note: The timer has two disadvantages. One is when there are multiple tasks, for example, the original second task is executed after 1 second, but the first task is executed after two seconds, then the second task must wait. Execute a task after execution.
Another thing is that when the first task reports an error, all the tasks in the timer hang up. This is a very serious consequence.

Timer timer=new Timer();
timer.schedule(线程,1000);//意思是1000毫秒之后执行线程


//如何解决这个问题呢?
//创建一个可调度的线程池
ScheduledExecutorService ExecutorService = Executors.newScheduleduledThreadPool(100);
EsxecutorService.schedule(线程,1000,TimerUnit.MILLISECONDS)//最后一个是指明1000的时间单位,这里是毫秒

Deadlock

Nested locks can cause deadlocks
solution: 1 Avoid nested locks, lock the nested sequence 2, 3 introduces a timeout mechanism

Lock

It is a kind of lock provided by java1.5, which can be controlled flexibly.

Lock lock=new ReentrantLock();     //创建一个可重入锁

//主要有两个方法
lock.lock();      //加锁
locak.unlock();  //解锁
ReentrantReadWriteLock rwl= new  ReentrantReadWriteLock() ;  //创建一个既可以读又可以写的锁
rwl.writeLock().lock()   //创建一个写锁, 只能一个线程进来
rwl.writeLock().unlock() //释放写锁

rwl.readLock().lock()   //创建一个读锁, 可以有多个线程进来
rwl.readLock().unlock() //释放读锁

Pessimistic locks and optimistic locks-database level

Pessimistic lock: only one thread in operation, whether read or write directly to the table locked, another thread could not come to realize statement
behind the increase for update

select * from user  for update

Optimistic locking: Add a version field to the table.

Distributed lock: redis zk

Published 281 original articles · 50 praises · 450,000 views +

Guess you like

Origin blog.csdn.net/lzh657083979/article/details/79365217