Multithreaded notes

Posted by vexious on Tue, 08 Feb 2022 09:08:05 +0100

Three elements of concurrent programming?

1) Atomicity

Atomicity refers to one or more operations that are either fully executed and not interrupted by other operations, or not executed at all.

2) Visibility

Visibility refers to that when multiple threads operate on a shared variable, after one thread modifies the variable, other threads can immediately see the modification results.

3) Order

Order, that is, the execution order of the program is executed according to the order of the code.

What are the ways to achieve visibility?

synchronized or Lock: ensure that only one thread obtains the Lock and executes the code at the same time. Before the Lock is released, refresh the latest value to the main memory to achieve visibility

What are the ways to create threads?

1) Inherit Thread class to create Thread class

2) Create thread class through Runnable interface

3) Creating threads through Callable and Future

4) Create from thread pool

What is a thread pool? What are the creation methods?

Thread pool is to create several threads in advance. If there are tasks to be processed, the threads in the thread pool will process the tasks. After processing, the threads will not be destroyed, but wait for the next task. Since creating and destroying threads consume system resources, when you want to create and destroy threads frequently, you can consider using thread pool to improve the performance of the system.
java provides a java util. concurrent. The implementation of the executor interface is used to create a thread pool.

Thread safety in singleton mode

1) Writing method of hungry Han style singleton mode: thread safety

2) Lazy singleton mode: non thread safe

3) Writing method of double check lock single instance mode: thread safety

Concurrency and parallelism

Thread safety: often used to describe a piece of code. In the case of concurrency, the code is used by multiple threads, and the scheduling order of threads does not affect any results. When using multithreading at this time, we only need to pay attention to the memory of the system and whether the cpu is enough. Conversely, thread insecurity means that the scheduling order of threads will affect the final result

public class Demo4 {
    /**
     * Cache thread pool (unlimited length)
     * Execution process after adding tasks
     * 1.Determine whether there are idle threads in the thread pool
     * 2.Use if present
     * 3.If it does not exist, create a thread and put it into the thread pool, and then use
     * @param args
     */
//    public static void main(String[] args) {
//        //Directs the execution of new tasks in the thread pool
//        ExecutorService service = Executors.newCachedThreadPool();
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day noon 1");
//            }
//        });
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day noon 2");
//            }
//        });
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day (noon 3");
//            }
//        });
//
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day at noon");
//            }
//        });
//    }

    /**
     * Fixed length linear pool
     * (Length is the specified value)
     * Implement process after adding tasks
     * 1.Determine whether there are idle threads in the thread pool
     * 2.Use if present
     *  3.If there are no idle threads and the thread pool is not full, create a thread and put it into the thread pool, and then use it
     *  4.When there are no idle threads and the thread pool is full, wait for idle threads in the thread pool
     */
//    public static void main(String[] args) {
//        ExecutorService service = Executors.newFixedThreadPool(3);
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day noon 1");
//
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day noon 2");
//
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day (noon 3");
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        });
//        service.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + "weeding day (noon 5");
//            }
//        });
//    }

                 /**
            *           One way thread pool
                  *           1.Determine whether the thread in the thread pool is idle
                  *           2.Use when idle
                  *           3.If it is not idle, wait for a single thread in the pool to be idle before using it
               */
//       public static void main(String[] args) {
//            ExecutorService service = Executors.newSingleThreadExecutor();
//            service.execute(new Runnable() {
//                @Override
//                public void run() {
//                    System.out.println(Thread.currentThread().getName() + "weeding day noon 1");
//                }
//            });
//           service.execute(new Runnable() {
//               @Override
//               public void run() {
//                   System.out.println(Thread.currentThread().getName() + "weeding day noon 2");
//               }
//           });
//           service.execute(new Runnable() {
//               @Override
//               public void run() {
//                   System.out.println(Thread.currentThread().getName() + "weeding day (noon 3");
//               }
//           });
//           service.execute(new Runnable() {
//               @Override
//               public void run() {
//                   System.out.println(Thread.currentThread().getName() + "weeding day (noon 4");
//               }
//           });
//       }

    /**
     * lambda expression
     * Reserved parameter - > reserved method body
     */
    public static void main(String[] args) {
        Thread t = new Thread(() ->{
            System.out.println("shuaige");
        });
        t.start();
    }
}

Topics: Java