java-multithreading basics

Multi-thread safety issues

In my impression, the more classic is that two people operate the same bank card at the same time. Note that the operation is at the same time, so what problems will arise.
Originally there were 10 million in the bank card. Zhang San was withdrawing 1 million while the other Li Si deposited 2 million. Then according to our normal thinking, it is 1000-100+200=111 million.
But when the two first read the balance in the same bank card at different counters, Zhang San saw that it was 10 million, and Li Si saw that it was also 10 million. After Zhang San had withdrawn the money, he read the balance again. It became 9 million (because Zhang San took 1 million). Li Si deposited 2 million, and then inquired 12 million. So is there a question of inaccurate balance, whether it is 9 million or 12 million.

Solution

The common method is to lock (synchronize) . What does it mean is that when multiple threads modify a shared resource at the same time, the person who acquires the resource first (acquires the lock) will monopolize the resource (lock), and other threads can only wait (block) after the current thread is modified. To proceed.
Note: Do not lock all resources (code). In this case, the thread that monopolizes the resource can run slowly, and other threads can only wait.

Method 1: Synchronize code blocks

The wording is as follows, this word is a bit difficult to write.


synchronized (obj) {
    
     // obj是指锁对象(需要唯一)
    //方法体里面就是线程独占执行的代码
}

Method 2: Synchronization method

Add synchronized before the return value, which means that the current method is exclusively owned by threads in the running state.
Common cases are: Hashtable, Vector, StringBuffer. These are not recommended in java. Although they are relatively safe, the performance is relatively low. We use hashmap and StringBuilder.

public synchronized void func(){
    
    
}

Deadlock problem

This is to add synchronized to multiple locations, one thread occupies a lock, another thread occupies another lock, and then when the execution to the next step, it will wait for the other side to exit, and then that's it, just like a traffic jam.

Thread communication (wait and wake up)

1.obj.wait(); The current thread exits from the running state and enters the waiting state. It must be awakened by obj.notify(); to get to the execution state to grab the time slice.

  • obj.wait(time); Waiting to be awakened or time is over to wake up.
  • The obj.notify() method wakes up the wait of the obj lock object. If there are more than one, one of them will be awakened randomly.
  • obj.notifyAll() wakes up all the waiting threads of obj objects.

Error-prone point: Whether it is the wait method or the notify method, the code execution must be synchronized in the thread.

The difference between sleep() and wait()

  1. Thread.sleep (number of milliseconds); only wait until the time is over, and obj.wait (number of milliseconds) is the execution state when the time ends or is awakened.
  2. Thread.sleep (number of milliseconds) sleeps with the lock if it is holding a lock when sleeping. Other threads cannot preempt the time slice and only wait; and obj.wait (number of milliseconds); exits the running state, that is, The lock is released, and other threads can take over the time slice.
  3. Sleep does not need to hold the lock when it is called (ie Thread.sleep (milliseconds); also needs to be in synchronized), and wait can be called only when it holds the lock.

Thread abort

Design a condition, for example, time == 50 to break. In fact, the termination must be done with a break statement.
This is not clearly written, and it will be written later.
Multithreading is really difficult.

Thread Pool

The pool is used to store a collection of objects. The role is to manage multiple objects to achieve the reuse of objects and reduce the time of new creation and destruction. Because Java is very resource intensive, this is innate. You see that writing Java code is much more than writing python, but the multi-platform feature of Java is very powerful.
The role of threads

  • You can set the upper limit of the number of threads.
  • Threads can be reused and put in the pool after each use, which is convenient for the next use.
  • Reduce the time of creation and destruction.

Write a thread pool that creates a fixed size.

	public static void main(String[] args) {
    
    
		
		Runnable runnable = new Runnable() {
    
    

			@Override
			public void run() {
    
    
				String name = Thread.currentThread().getName(); //主线程
				for( int i = 0 ; i < 5 ; i++) {
    
    
					System.out.println(name +"运行次数"+i);
				}
			}
		};
		ExecutorService service = Executors.newFixedThreadPool(4); //创建一个固定大小的,这里是只有4个的线程池
		//下面是给线程池中4个线程,7个任务,那么最多4个线程同时运行,还有三个线程一开始需要等待
		service.submit(runnable);
		service.submit(runnable);
		service.submit(runnable);
		service.submit(runnable);
		service.submit(runnable);
		service.submit(runnable);
		service.submit(runnable);
		
		service.shutdown();
		}

Lock interface and commonly used implementation classes

The lock() interface has the same function as synchronized, which is to lock.

Write here first, write later

Guess you like

Origin blog.csdn.net/toomemetoo/article/details/112969661