Java Concurrency arts reading notes

As a multi-threaded Java development level of the Bible book, read the first pass tidy up the directory structure of the book knowledge, knowledge point for subsequent review and self-examination;
Here Insert Picture Description

Context switching

When the CPU cycle time slice allocation algorithm executed by the task, the current will switch to the next task after task execution time slice, but before the switch will save the state before switching tasks for the next switch back to this task, this task can be loaded state, the task is to save the process of reloading a context switch.

Reducing context switching

  1. Lock-free concurrent programming
  2. CAS algorithm
  3. With a minimum thread
  4. Use coroutine - i.e., multi-task scheduling in a single thread.

Deadlock code sample

/**
 * @author zhengzheng046
 */
public class DeadLockDemo {

    private static String A = "A";
    private static String B = "B";

    public static void main(String[] args) {
        new DeadLockDemo().deadLock();
    }

    private void deadLock() {
        Thread t1 = new Thread(() -> {
            synchronized (A) {
                try {
                    System.out.println("当前线程名:" + Thread.currentThread().getName());
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B) {
                    System.out.println("1");
                }

            }
        });

        Thread t2 =new Thread(()->{
            synchronized (B){
                System.out.println("当前线程名:"+Thread.currentThread().getName());
                synchronized (A){
                    System.out.println("2");
                }
            }
        });

        t1.start();
        t2.start();
    }

}
Published 21 original articles · won praise 4 · Views 511

Guess you like

Origin blog.csdn.net/weixin_39617728/article/details/104871845