Basic concepts: program, process, thread

Application:

A program is a collection of instructions written in a language to accomplish a specific task. A static piece of code, a static object.

Process:

A process is an execution of a program, or a running program. Is a dynamic process: it has its own process of birth, existence and extinction. — Life cycle

  • Such as: running QQ, running MP3 player…
  • Programs are static and processes are dynamic
  • Process as the unit of resource allocationAt runtime, the system allocates a different memory area for each process

Thread:

A process can be further refined into a thread, which is an execution path within a program.

  1. Each thread has its own independent: virtual machine stack, program counter
  2. Multiple threads, sharing structures in the same process: method area, heap
  • Multithreading is supported if a process executes multiple threads in parallel at the same time

  • Thread as the unit of scheduling and execution, each thread has an independent running stack and program counter (PC), the overhead of thread switching is small

  • Multiple threads in a process share the same memory unit/memory address space -> they allocate objects from the same heap and can access the same variables and objects. This makes the communication between threads easier and more efficient. But multiple threads operating on shared resources can be a security risk.

Single-core CPU and multi-core CPU understanding

  • A single-core CPU, in fact, is a false multithreading, because only one thread of work can be executed in a unit at a time.
  • If it is multi-core, can better play the efficiency of multi-threading.
  • A Java application java.exe has at least three threads: main(), garbage collector () thread, exception handler thread; Of course, if an exception occurs, the main thread will be affected.

Parallelism and concurrency

  • Parallel: Multiple cpus perform multiple tasks at the same time. For example: multiple people doing different things at the same time
  • Concurrency: one CPU(using time slices) executes multiple tasks at the same time. For example: second kill, more than one person to do the same thing

Advantages of using multiple threads

  • Improving application responsiveness; Makes more sense for a graphical interface, detests a strong user experience.
  • Improve the CPU utilization of computer system
  • Improving the process structure; Long and complex processes are divided into multiple threads and run independently, making it easier to understand and modify.

When do you need multithreading

  • Programs need to perform two or more tasks simultaneously
  • The program needs to realize some tasks that need to wait, such as user input, file read and write operations, network operations, search, etc..
  • Need some background running programs

Thread creation and use *****

Thread creation: Method one inherits the Thread class

Methods of the Thread class

Void start() : Starts the thread and executes the object’s run() method

Run () : Operation performed when a thread is called after it has been started

  • You typically override this method in the Thread class to declare the operations that the current Thread needs to perform in this method

String getName() : Returns the name of the thread

  • Gets the name of the current thread

Void setName(String name) : Sets the thread name

  • Sets the name of the current thread

Static Thread currentThread() : returns the currentThread; In the Thread subclass this is commonly used for the main Thread and Runnable implementation classes

  • Static method that returns the thread executing the current code

Yield () : Releases the execution of the current CPU

  • Releases execution from the current CPU, but may be assigned to the current thread at the next moment

join()

  • After thread B.join () is called in thread A, thread A is blocked, and thread A does not stop blocking until thread B completes its execution

Stop () : forcibly terminates the life cycle of the current thread. Deprecated

Sleep (Long Millitime) : Static method that suspends the current thread for a period of time millitime(blocking)

  • Millitime The current thread is blocked for the specified period of time

IsAlive () : checks whether the current thread isAlive

  • The current thread will die if the run() method completes execution

Priority level of a thread

  • MAX_PRIORITY: 10 — maximum
  • MIN_PRIORITY: 1 — minimum
  • NORM_PRIORITY: 5 — default

Gets and sets the priority of the thread

  • getPriority()
  • setPriority(int p)
Note: a thread with a higher priority preempts the CPU of a thread with a lower priority. But in terms of probability, a high-priority thread is executed with a high probability; It does not mean that the low-priority thread executes only when the high-priority thread finishes.
class HelloThread {
	public void run (a) {
    	for (int i = 0; i < 100; ++i) {
        	if (i % 2= =0) {
            	System.out.println(Thread.currentThread().getName() + ':' + i);
            }
            if(0 == i % 20) { yield(); }}}}public class ThreadMethodTest {
	public static void main (String[] args) {
    	HelloThread h1 = new HelloThread();
        h1.setName("Hello - 1");
        h1.start();
        Thread.currentThread().setName("main - 1");
        
        System.out.println("isAlive: " + h1.isAlive());
        
        for (int i = 0; i < 100; ++i) {
        	if (i % 2= =0) {
            	System.out.println(Thread.currentThread().getName() + ':' + i);
            }
            if (i == 20) { Thread.currentThread().join(); }}// Hello - 1 : ...
        // main - 1 : ...}}Copy the code

Thread creation and enablement

  • The JVM for the Java language allows a program to run multiple threads, as represented by the java.lang.Thread class
  • The Thread class features:
    1. Each Thread passes through a specific Thread objectThe run () methodTo complete the operation, often willrun()The body of the method is calledThe thread body
    2. Passes through the Thread objectStart () methodTo start the thread instead of calling run() directly

Inheriting from the Thread class

  1. Create a subclass that extends from Thread
  2. Override the Run () method of the Thread class –> declare the operations performed by this Thread in the run() method
  3. Object that creates a subclass of Thread
  4. Call start() with this object
    • Start the current thread
    • Call the run() method

Note:

  • You cannot start a thread by calling the run() method directly; you must call the start() method to start a new thread
  • When a thread needs to start again and iterate over numbers less than 100, it should not be started by a thread that has already started (). Complains IllegalThreadStateException, can create a thread object to execute the start again ()
// Inherits the thread class
// Count all the even numbers in 100
class MyThread extends Thread {
	public  void run (a) {
    	System.out.println("run");
    	for (int i = 0; i <= 100; ++i) {
        	if (i % 2= =0) {
            	System.out.println("i = "+ i); }}}}public class ThreadTest {
	public static void main (String[] args) {
    	MyThread mt = new MyThread();
        System.out.println("before");
        mt.start();
        System.out.println("after");
        // before
        // after
        // run
        // i = ...}}Copy the code

Scheduling of threads

Scheduling policy

  • Time slice: Occupies CPU by time slice

  • Preemptive: high-priority threads preempt the CPU

Java scheduling method

  • Threads of the same priority form a first-in, first-out queue (first-come, first-served) using a time slice policy
  • For high priorities, preemptive scheduling is used

Priority level of a thread

  • MAX_PRIORITY: 10
  • MIN_PRIORITY: 1.
  • NORM_PRIORITY: 5

Methods involved

  • GetPriority () : Returns the thread priority value
  • SetPriority (int newPriority) : Changes the priority of a thread

instructions

  • Thread creation inherits the priority of the parent thread
  • A low priority is simply a low probability of getting a schedule and is not necessarily called after a high priority thread

Thread creation: Method two to implement the Runnable interface

The Runnable interface

  • Create a class that implements the Runnable interface
  • Implementation class to implement the abstract method run() of the Runnable interface
  • Create an instance of this implementation class
  • Create an instance of Thread and use the implementation instance as an argument to the Thread instance
  • Call the start() method from an instance of Thread
/** * Implement the Runnable interface * 1. Create a class that implements the Runnable interface. 2. Implement the Runnable class's abstract method run() * 3. Create an object of the implementation class * 4. Pass this object as an argument to the constructor of Thread, and create an object of Thread * 5. Call the start() method * * from the Thread object@author lv
 * @createThe 2020-11-26 19:08 * /
class RThread implements Runnable {
    @Override
    public void run(a) {
        for (int i = 0; i <= 100; i++) {
            if (0 == i % 2) {
                System.out.println(Thread.currentThread().getName() + The '-' + Thread.currentThread().getPriority() + ":"+ i); }}}}public class ThreadTest1 {
    public static void main(String[] args) {
        RThread r1 = new RThread();
        Thread t1 = new Thread(r1);
        t1.setName("r-t");
        t1.start();
        Thread t2 = newThread(r1); t2.setPriority(Thread.MAX_PRIORITY); t2.start(); }}Copy the code

A comparison of two ways to create a thread:

Preferred in development: how to implement the Runnable interface

The reason:

  • The implementation does not have the limitations of a single inheritance of a class
  • The implementation is better suited for cases where multiple threads have shared data

Contact:

  • Public class Thread implements Runnable

Similarities:

  • Either way, you override the run() method and declare the logic to be executed in the run() method

Classification of threads

Threads in Java fall into two categories: daemon threads and user threads

Image understanding: rabbit dead dog cook, birds all bow hide

Thread life cycle ****

The process from birth to death of a structure

The JDK uses the Thread.State class to define several states of threads

  • New: When an object of the Thread class or its subclass is declared and created, the newly created Thread object is in the new state

  • Ready: a thread in the newly created state is queued to wait for a CPU slice after being started (). It is ready to run but has not been allocated CPU resources

  • Run: When a ready thread is scheduled and CPU resources are acquired, the run() method defines thread-like operations and functions

  • Blocking: In a special case, when an input/output operation is manually suspended or executed, the CPU is relinquish and its execution is temporarily terminated

  • Death: a thread has completed all of its work or the thread is forced to terminate or an exception occurs resulting in termination

Thread state transition

-new-> New – call start()-> Ready – get CPU execution right/lose CPU execution right, yield()-> Run – execute run, call stop(), Error-> die

– > run – sleep (), the join (), wait for synchronization lock, wait (), suspend () – > block – sleep time, the join () the end, acquiring the synchronization lock, notify ()/notify () and resume () – > ready – >…

Thread synchronization (security issues) *****

In Java, we address thread-safety issues through synchronization

Method 1: Synchronize code blocks

synchronized(Synchronization monitor) {// The code to synchronize
}
Copy the code

Description:

  • Code that operates on shared data is code that needs to be synchronized
    • You can’t include more code, and you can’t include less code
  • Shared data: Variables that are operated on by multiple threads
  • Synchronization monitor: commonly known as’ lock ‘; An object of any class can act as a lock
    • Requirement: Multiple threads must share one lock, unique
  • In the case of creating multiple threads using the implementation Runnable interface class, consider using this to act as a synchronization monitor
  • Avoid using this as a synchronization monitor when creating multiple threads using the inherited Thread class. Consider using the current class as a synchronization monitor such as window.class
class Window implements Runnable {
	private int ticket = 100;
    private Object obj = new Object();
    
    public void run (a) {
    	synchronized (obj) {
        	while (true) {
            	if (ticket > 0) {
                    System.out.println(ticket);
                    ticket++;
                } else {
                	break;
                }
            }
        }
    }
}
public class WindowTest {
	public static void main (String[] args) {
    	Window w1 = new Window();
        Thread t1 = new Thread(w1);
        Thread t2 = newThread(w2); t1.start(); t2.start(); }}** ** ** ** ** ** ** ** ** ** **@author lv
 * @createThe 2020-11-25 and * /
class Window2 extends Thread {
    private static int ticket = 100;
    private static final Object OBJ = new Object(); / / synchronization locks

    public void run(a) {
        while (true) {

Synchronized (OBJ) {// synchronized (OBJ)
            synchronized (Window2.class) { Window2.class -> Classes are also objects

                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        System.out.println("sleep2" + e.getMessage());
                    }
                    System.out.println(getName() + "Ticket number:" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}

public class WindowTest2 {
    public static void main(String[] args) {
        Window2 t1 = new Window2();
        Window2 t2 = new Window2();
        Window2 t3 = new Window2();

        t1.setName("window1");
        t2.setName("window2");
        t3.setName("window3"); t1.start(); t2.start(); t3.start(); }}Copy the code

Method 2: Synchronization method

If the code for the shared data of the operation is fully declared in a method, declare that method synchronous

  • The synchronization method still refers to the synchronization monitor, just without the declaration we display
  • A non-static synchronization method, the synchronization monitor is: this; Static synchronization monitor is the current class itself, such as Window4.class
package com.atguigu.java;

/** * Use synchronous methods to solve thread safety problems implementing the Runnable interface ** *@author lv
 * @createThe 2020-11-28 * / calm
class RThread3 implements Runnable {
    private int ticket = 100;

    @Override
    public void run(a) {
        while (true) { show(); }}public synchronized void show (a) {
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + ":"+ ticket); ticket--; }}}public class WindowTest3 {
    public static void main(String[] args) {
        RThread3 r = new RThread3();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        Thread t3 = new Thread(r);
        t3.setPriority(6); t1.start(); t2.start(); t3.start(); }}package com.atguigu.java;

** Thread safety problem ** Thread safety problem ** Thread safety problem **@author lv
 * @createThe 2020-11-25 and * /
class Window4 extends Thread {
    private static int ticket = 100;
    private static boolean isLoop = true;
    private static final Object OBJ = new Object(); / / synchronization locks

    public void run(a) {
        while(isLoop) { show(); }}private static synchronized void show (a) { // static The synchronization monitor is Window4.class
// private synchronized void show () {this is not a synchronized error
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("sleep2" + e.getMessage());
            }
            System.out.println(Thread.currentThread().getName() + "Ticket number:" + ticket);
            ticket--;
        } else {
            isLoop = false; }}}public class WindowTest4 {
    public static void main(String[] args) {
        Window4 t1 = new Window4();
        Window4 t2 = new Window4();
        Window4 t3 = new Window4();

        t1.setName("window1");
        t2.setName("window2");
        t3.setName("window3"); t1.start(); t2.start(); t3.start(); }}Copy the code

The singleton pattern

package com.atguigu.java1;

/** * Rewrite lazy singleton patterns to thread-safe ** using synchronization@author lv
 * @createThe 2020-11-29 part * /
class Bank {
// Declare instance variables
    private static Bank instance = null;
// 1. Privatize the constructor
    private Bank (a) {}

Public static synchronized Bank getInstance () {// Synchronized Bank.class
    public static Bank getInstance (a) {
// Method 1: less efficient
// synchronized (Bank.class) {
// if (instance == null) {
// instance = new Bank();
/ /}
// return instance;
/ /}
// Method 2: Be more efficient
        if (instance == null) {
            synchronized (Bank.class) {
                if (instance == null) {
                    instance = newBank(); }}}returninstance; }}public class BankTest {}Copy the code

Mode 3: Lock – JDK5.0 New

  • Starting with JDK5.0, Java provides a more powerful thread synchronization mechanism — synchronization is achieved by explicitly defining a synchronization lock object; A synchronous Lock is acted by using a Lock object.
  • Java. Util. Concurrent. The locks. Lock interface is the tool of control multiple threads to Shared resources access; A Lock provides exclusive access to a shared resource. Only one thread at a time can Lock the Lock object. The thread must acquire the Lock object before starting to access the shared resource.
  • The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized. In the implementation of thread-safe control, ReentrantLock is more commonly used, which can display Lock, Lock release.
package com.atguigu.java1;

import java.util.concurrent.locks.ReentrantLock;

/** * New * 1 in JDK5.0. Instantiate ReentrantLock * 2. Call the lock() method - similar to the current thread getting the synchronization monitor * 3. Call the unlock() method to unlock * *@author lv
 * @createThe 2020-11-29 15:42 * /
class Window implements Runnable {
    private int ticket = 100;
    / / 1.
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run(a) {
        while (true) {

            try {
                / / 2.
                lock.lock();
                if (ticket > 0) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":" + ticket);
                    --ticket;
                } else {
                    break; }}finally {
                / / 3.lock.unlock(); }}}}public class LockTest {
    public static void main(String[] args) {
        Window w = new Window();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = newThread(w); t1.start(); t2.start(); t3.start(); }}Copy the code

Similarities and differences between synchronized and Lock *****

Preference order: Lock -> synchronize code block -> synchronize methods

The same:

  • Both address thread safety issues

Different:

  • The synchronized mechanism automatically releases the synchronization monitor after executing the corresponding synchronization code
  • Lock starts synchronization Lock () manually, and ends synchronization with unlock() manually

How do you solve thread-safety problems?

  • Lock and synchronized

Thread deadlock issues

Deadlock:

  • Different threads occupy the synchronization resources needed by the other party and do not give up. Each thread is waiting for the other party to give up the synchronization resources needed by itself, thus forming a thread deadlock
  • After a deadlock occurs, there are no exceptions, no prompts, but all threads are blocked and cannot continue

Solutions:

  • Special algorithms, principles
  • Minimize the definition of synchronized resources
  • Try to avoid nested synchronization

Thread communication ****

Operations on shared data

package com.atguigu.java2;

/** * Thread communication: two threads alternately print 1-100 data ** Three communication methods involved ** Wait () : Once this method is executed, the current thread will block and release the synchronization monitor ** notify() : NotifyAll () : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() : notifyAll() * * 1. The callers of wait, notify, and notifyAll must be synchronous code blocks or synchronization monitors. 3. Wait, notify, and notifyAll are defined in java.lang.Object@author lv
 * @createThe 2020-11-29 "* /
class PrintNum implements Runnable {
// private int num = 100;
    private int i = 1;
    private Object obj = new Object();
    @Override
    public void run(a) {
        while (true) {
// synchronized (this) {
            synchronized (obj) {
// this.notify();
                obj.notify();
                if (i <= 100) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    ++i;
                    try {
// this.wait();
                        obj.wait();
                    } catch(InterruptedException e) { e.printStackTrace(); }}else {
                    break;
                }
            }
        }
    }
}
public class CommunicationTest {
    public static void main(String[] args) {
        PrintNum p = new PrintNum();
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(p);
        t1.setName("t1");
        t2.setName("t2");
        t1.setPriority(7); t2.start(); t1.start(); }}Copy the code

Similarities and differences between sleep and wait *****

Similarity: Once executed, the current thread can be blocked

Difference:

  1. The two methods declare different positions
    • Declare sleep() in Thread
    • Wait () declared in the Object class
  2. Call requirements are different
    • Sleep () can be called in any scenario needed
    • Wait () must be used in synchronized code blocks, synchronized methods
  3. Whether the synchronization monitor is released: sleep() does not release the lock, wait() does
package com.atguigu.java2;

/** * Producer, seller, consumer, product **@author lv
 * @createWhy do * / 2020-11-30

class Clerk {

    private int productCount = 0;
    public synchronized void produceProduct(a) { // this

        if (productCount < 20) {
            productCount++;
            System.out.println(Thread.currentThread().getName() + " : start produce " + productCount + " product");
            notifyAll();
        } else {
            // wait
            try {
                wait();
            } catch(InterruptedException e) { e.printStackTrace(); }}}public synchronized void consumeProduct(a) { // this

        if (productCount > 0) {
            System.out.println(Thread.currentThread().getName() + " : start consume " + productCount + " product");
            productCount--;
            notifyAll();
        } else {
            // wait
            try {
                wait();
            } catch(InterruptedException e) { e.printStackTrace(); }}}}class Producer extends Thread {

    private Clerk clerk;

    public Producer (Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run(a) {
        System.out.println("start produce product");
        while (true) {
// try {
// Thread.sleep(20);
// } catch (InterruptedException e) {
// e.printStackTrace();
/ /}clerk.produceProduct(); }}}class Customer extends Thread {

    private Clerk clerk;

    public Customer (Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run(a) {
        System.out.println("start consume product");
        while (true) {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
/ /}clerk.consumeProduct(); }}}public class ProductTest {
    public static void main(String[] args) {

        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);
        Producer p2 = new Producer(clerk);
        Customer c1 = new Customer(clerk);
        p1.setName("p1 ");
        p2.setName("p2 ");
        c1.setName("c1 "); p1.start(); p2.start(); c1.start(); }}Copy the code

JDK5.0 New thread creation method *****

Interviews: There are four ways to create multiple threads

Method 1: Implement the Callable interface

Callable is more powerful than Runnable

  • Call () can have a return value compared to the run() method
  • The call() method can throw an exception, which can be caught outside to get the exception information
  • Callable supports generic return values
  • You need the FutureTask class, for example, to get the return result

The Future interface

  • You can cancel the execution result of a Runnable or Callable task, query whether the task is complete, and obtain the result
  • FutureTask is the only implementation class for the Future interface
  • FutureTask implements both Runnable and Future interfaces. It can be either executed by the thread as a Runnable or returned by a Callable as a Future
package com.atguigu.java2;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/** * Thread creation method 3: implement Callable interface **@author lv
 * @createThe 2020-12-02 19:04 * /
Create an implementation class that implements Callable
class NumThread implements Callable {
// 2. Implement the call() method, similar to run()
    @Override
    public Object call(a) throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2= =0) { System.out.println(i); sum += i; }}// integer
        returnsum; }}public class ThreadNew {
    public static void main(String[] args) {
// 3. Create an object for the Callable interface implementation class
        NumThread n1 = new NumThread();
// 4. Pass the object of this Callable interface implementation class as a parameter to FutureTask
        FutureTask f1 = new FutureTask(n1);
// 5. Pass the FutureTask object as an argument to the Thread constructor, create the Thread object, and call start()
        new Thread(f1).start();

        try {
// Get the return value of the call method in Callable
            // sum is the return value of get() and the return value of FutureTask constructor Callable that implements the class rewrite call() method
            // Discard the return value without calling get()
            Object sum = f1.get();
            System.out.println("sumAll: " + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch(ExecutionException e) { e.printStackTrace(); }}}Copy the code

Method 2: Use a thread pool

Thread pool-related apis

  • JDK5.0 provides thread pool-related apis: ExecutorService and Executors

  • ExecutorService: A true thread pool interface; The common subclass, ThreadPoolExecutor

    1. Void execute(Runnable command) : executes a task or command. No return value is returned. It is used to execute Runnable
    2. Futuresubmit(Callabletask) : Performs the task, returns a value, and typically performs the Callable
    3. Void shutdown() : shuts down the connection pool
  • Executors: Factory classes for tools and thread pools, used to create and return different types of thread pools

    1. Executors. NewCachedThreadPool () : create a according to the need to create a new thread’s thread pool
    2. Executors. NewFixedThreadPool (n) : create a reusable fixed number of threads in the thread pool
    3. Executors. NewSingleThreadExecutor () : only one thread to create a thread pool
    4. Executors. NewScheduleThreadPool (n) : create a thread pool, it can be arranged in a given delay or run the command to perform on a regular basis

Background:

Extremely heavy resources that are frequently created and destroyed, such as threads in concurrent situations, have a significant impact on performance

Ideas:

Create a lot of threads in advance, put them into the thread pool, get them directly when using, and put them back into the pool after using. It can avoid frequent creation and destruction and realize reuse. Similar to public transportation in life

Benefits:

  • Improved response times (reduced time to create new threads)
  • Reduced resource consumption (reusing threads in the thread pool to avoid each creation)
  • Easy thread management
    1. CorePoolSize: Size of the core pool
    2. MaxmumPoolSize: indicates the maximum number of threads
    3. KeepAliveTime: The maximum amount of time a thread can hold without a task before terminating
package com.atguigu.java2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/ * * *@author lv
 * @createThe 2020-12-02 is their * /
class RThread1 implements Runnable {
    @Override
    public void run(a) {
        for (int i = 0; i <= 100; i++) {
            if (i % 2= =0) {
                System.out.println("i = "+ i); }}}}class RThread2 implements Runnable {
    @Override
    public void run(a) {
        for (int i = 0; i <= 100; i++) {
            if (i % 2! =0) {
                System.out.println("i = "+ i); }}}}public class ThreadPool {
    public static void main(String[] args) {
        // 1. Provide a thread pool with the specified number of threads
        ExecutorService service = Executors.newFixedThreadPool(10);
        System.out.println(service.getClass());
        ThreadPoolExecutor ser = (ThreadPoolExecutor)service;
        ser.setCorePoolSize(15);
// ser.setKeepAliveTime();
        // 2. Execute the specified thread operation; You need to provide an implementation-class object that implements the Runnable or Callable interfaces
        service.execute(new RThread1()); // Suitable for Runnable
        service.execute(new RThread2());
// service.submit(Callable callable); Suitable for Callable, get the return value
        // 3. Disable the connection pool
        service.shutdown(); // Close the connection pool}}Copy the code

The problem

Talk about your understanding of programs, processes and threads

1. A collection of instructions written in a language to accomplish a specific task; A static piece of code

Process: an execution of a program, or a running program

Thread: A process can be further refined to a thread, which is an execution path within a program

Talk about your understanding of Project and Module in IDEA

  • Project = e.walker space: Is a Project
  • Module = E.project: is a Module in a project

Thread communication

The following three methods are defined in the Object class

  • wait()
  • notify()
  • notifyAll()

The synchronization code block relates to synchronization monitor and shared data, talk about your understanding of synchronization monitor and shared data, and points to pay attention to

Synchro monitor

  • The synchronization monitor must be unique to the same thread
  • Objects of any class can be used as synchronization monitors
  • Synchronization monitors can use this, class.class, and so on

Sharing data:

  • Data that is operated on by multiple threads
  • Use synchronization methods of threads to manipulate shared data

The difference between sleep() and wait()

sleep

  • Different locations: Sleep is declared in Thread, wait is declared in Object
  • Wait can only be used in synchronized code and methods. Sleep is not required
  • The wait method causes the current thread to release the synchronization monitor, but sleep does not
  • The wait method uses notify or notifyAll to wake up threads

The singleton pattern

/ / LanHanShi
public class Person {
	private static Person instance = null;
	private Person (a) {}
    public static Person getInstance (a) {
    	if (instance == null) {
    		synchronized (Person.class) {
        		if (instance == null) {
            		instance = newPerson(); }}}return instance
    }
    
}
Copy the code

The life cycle

The main concerns are: state, corresponding methods

  • Which methods are executed for state changes (callback methods)
  • A change in state after a method is executed
  • A blocked state is a temporary state, not a final state
  • Death: Final state

How many ways can you create multiple threads? Four ways

  • Thread class inheritance
  • Implement the Runnable interface
  • Implement Callable interface
  • Creating a thread pool
    1. Improve response speed
    2. Improve resource reuse
    3. Facilitate the management

Comparison of synchronized and Lock approaches to thread safety

Same: Both address thread-safety issues

Different:

  1. The synchronized mechanism automatically releases the synchronization monitor after executing the corresponding synchronization code
  2. Lock mechanism requires manual other dynamic synchronization lock(), after synchronization and manually end synchronization unlock()