Thread factory mode

Process: the smallest unit allocated and scheduled by system resources, while thread depends on the existence of process and the smallest unit of program execution!

If a thread is created ---- there must be a process ----- > create system resources
* the Java language cannot create system resources and operates with the help of the underlying language C
* Java provides Thread class
 *
* how to create a Thread with the help of Thread class?
 *
 *
* Concurrency: occurs simultaneously at a point in time
* parallel: simultaneous occurrence within a time period
 *
 *
* development steps:
* 1) customize a class inherited from thread (thread is the execution thread in the program. Java virtual machine allows applications to run multiple execution threads concurrently.)
* 2) this subclass should override the run method of Thread class
* 3) create the current subclass object and start the thread: start() instead of run method ()
 *
* start thread: use the start method
* membership method:
* set thread name
 *          public final void setName(String name)
* get thread Name:
 *          public final String getName()

public class ThreadDemo {

    public static void main(String[] args) {

        //Create subclass object
        MyThread my = new MyThread() ;

        //Start thread
        //This one thread object calls the run method twice
      //  my.run();
      //  my.run();

        my.setName("Yang Decai");
        my.start(); //The start method is called by calling the run method through the jvm
        //my.start(); //IllegalThreadStateException: illegal state exception

        MyThread my2 = new MyThread() ;
        my2.setName("Gao Yuanyuan") ;
        my2.start();
    }
}

public static void yield(): pause the thread currently executing and execute other threads!

public final void join()
* throws InterruptedException: wait for the thread to terminate

Constant field table of Thread class
 * public static final int MAX_PRIORITY 10
 *  public static final int MIN_PRIORITY 1
 *  public static final int NORM_PRIORITY 5: default value
 *
* public final void setPriority(int newPriority) sets the priority
 *  public final int getPriority()
 *
 *
* the higher the priority, the more qualified the thread is to seize the execution right of the cpu (the cpu can switch efficiently with a little time slice)
* threads with lower priority: the smaller the preemption of CPU execution right!
 *
* the execution of threads is random! The default is 5

tp1.setPriority(10);
        tp2.setPriority(1);
        System.out.println(tp3.getPriority());//5

The Java language cannot enable multithreading

What are processes and threads
Process:
The basic unit of system resource allocation and scheduling! (the "entity" of the procedure)
Thread must rely on the process to exist. It is the basic unit of program execution!     
A process is composed of many thread groups. A thread group contains many threads (a collection of threads!)
    
Multithreading --- the execution of each thread is random and forces the execution right of the CPU (only qualified for execution)

2. How to create multithreading? Please describe the steps
Mode 1:
Use inheritance relationship:
1) customize a class, which inherits from Thread class (Thread class)
2) Rewrite the run method: the jvm calls the run method by starting the thread
3) create the current class object in the user thread (main), and start the thread: start()

3. Traversal method of map set
Two kinds
1) get the set of all keys: set < k > keyset() (recommended)
Traverse all keys -- V get(Object K): get the value through the key
                    
2) get all key value pair objects: set < map entry<K,V>> entrySet() 
Traverse all key value pair objects: get keys and values through key value pair objects
                                K getKey()
                                V getValue()

4. How to implement natural sorting and comparator sorting in TreeSet < E > Set
If TreeSet < E > wants to realize natural sorting, create the current class object TreeSet < E > () through the parameterless construction method
Conditions must be met: the type of current storage must implement the interface Comparable interface
Rewrite the CompareTo (T) method in the comparable interface
        
If TreeSet < E > implements comparator sorting: create the current class object TreeSet < E > (comparator < E > com) through parametric construction
        
1) the user-defined class implements Comparator < E > and rewrites compare(T t1,T t2) of Comparator interface
2) when creating the current class object, directly use the interface anonymous internal class
Formal parameters:
                    new Comparator<E>(){
Rewrite compare(T t1,T t2){
Sorting rules
                            }
                    } ;

5. What is the difference between final and finalize?
final: status modifier
Modifier class, cannot be inherited
Modifier method: cannot be overridden
Modifier variable: is a constant
        
        
finalize: it is a method of the Object class: when the Object is currently created, if the Object has no more references, it is used up,
Wait for GC to recycle unused objects. When GC is started, it will call the finalize() method to recycle and free up the occupied space!
        
        
        
GC garbage collection algorithm
JVM optimization mechanism
        
        
SQL optimization (SQL tuning)
web server tuning

Multithreading implementation mode 1:   Inheritance relationship
     SellTicket st1 = new SellTicket() ;
            SellTicket st2 = new SellTicket() ;
            SellTicket st3 = new SellTicket() ;

            //Set thread name
            st1.setName("Window 1") ;
            st2.setName("Window 2") ;
            st3.setName("Window 3") ;

            //Start thread
            st1.start() ;
            st2.start() ;
            st3.start();

            Three stacks point to three heaps:100 tickets are on sale "No data sharing"
Inheritance has limitations--->rewrite run method----->Thread Class run---->Through implementation Runnable Interfaced run method
    Not just inheritance run method,It also inherits other irrelevant methods,It is not conducive to the expansion of functions! (Not reflected:Interface oriented programming)



Multithreading implementation mode 2: (recommend)
            "resource sharing"
            Each thread is using the same object st(SellTicket Object reference) embody "Interface oriented programming"
            Static proxy mode
                    Biggest feature:Both the real role and the proxy class must implement the same interface!
                    Proxy classes enhance the functions of real characters!
            proxy class
            Real role

            SellTicket realization Runnable Interface complete run Method rewrite
            Thread Class itself Runnable Interface complete run Method rewrite



                 SellTicket st = new SellTicket() ;
                //Create multiple thread class objects and pass the resource sharing class as a parameter
                Thread t1 = new Thread(st,"Window 1") ;
                Thread t2 = new Thread(st,"Window 2") ;
                Thread t3 = new Thread(st,"Window 3") ;



                //Start thread
                t1.start();
                t2.start();
                t3.start();

Implementation mode of multithreading 2) implementation relationship (Runnable) (key)


 *
* steps:
* 1) customize a class, implement the Runnable interface, and rewrite the run method
* 2) create the current "resource class" object in the user thread (main)
* then create a Thread class object and pass the "resource class" object as a parameter
 *
 *  public Thread(Runnable target,String name)
* 3) start threads separately
 *
 *
* / / static function of Thread class
* public static Thread currentThread(): refers to the reference of the thread object being executed

public class ThreadDemo {
    public static void main(String[] args) {

        //Create resource class object
        MyRunnable my = new MyRunnable() ;//shared resource

        //Create thread class object
        Thread t1 = new Thread(my,"t1") ;
        Thread t2 = new Thread(my,"t2") ;
        Thread t3 = new Thread(my,"t3") ;

        //Start thread
        t1.start();
        t2.start();
        t3.start();


    }


}
realization runnable Interface
public class MyRunnable implements  Runnable{

The cinema has three windows, a total of 100 tickets, using multithreaded simulation!

public class SellTicket  extends  Thread{

    //There are 100 tickets
    public static int tickets = 100 ;
    //Create a lock
    private Object obj = new Object() ;

    @Override
    public void run() {
        //There are always tickets
        while(true){
            synchronized (obj){
                //Join the network delay and sleep for 100ms
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(tickets>0){
                    System.out.println(getName()+"In the process of sale"+tickets+"Tickets");
                    tickets -- ;
                }else{
                    break ;
                }
            }


        }
    }
}
public class SellTicketDemo {

    public static void main(String[] args) {

        //Create three threads
        SellTicket st1 = new SellTicket() ;
        SellTicket st2 = new SellTicket() ;
        SellTicket st3 = new SellTicket() ;

        //Set thread name
        st1.setName("Window 1") ;
        st2.setName("Window 2") ;
        st3.setName("Window 3") ;

        //Start thread
        st1.start() ;
        st2.start() ;
        st3.start();
    }
}

v

"tickets": random execution of threads "
/ / t1 come first and record the previous value: 100
/ / when t1 records 100 data, t2 comes in when preparing -- and may output the 100 value recorded before t1, and 100 appears in the same ticket

/ / the second case: negative ticket
/ / current t1 thread - ticket 2
/ / sleep for 100ms
/ / t3 thread preempted the first ticket -- > (record 2 of t1 thread -- complete --)
/ / T1, T2, T3 ---- > T2 seize 1 before ---- > record first, and then change to 0 tickets after completion
/ / when the value recorded in the current memory has not output 0, after t1 preempts, record t2, record 0 tickets, the number of votes of t1 --, and - 1 appears

The second way can reflect "resource sharing"
 *
* the program appears:
* 1) a ticket may be sold many times (the same ticket appears)
* the execution of threads is random (atomic operation: the simplest and most basic operation statements: -, + +...)
* 2) negative votes
* caused by the latency of the thread (join sleep for 100ms)
* there is a "multi thread safety problem" in the current program

public class SellTicketDemo {
    public static void main(String[] args) {


        //Create resource sharing class object
        SellTicket st = new SellTicket() ;
        //Create multiple thread class objects and pass the resource sharing class as a parameter
        Thread t1 = new Thread(st,"Window 1") ;
        Thread t2 = new Thread(st,"Window 2") ;
        Thread t3 = new Thread(st,"Window 3") ;

        //Start thread
        t1.start();
        t2.start();
        t3.start();
    }
}

Although the current program can reflect "resource sharing", the program gives negative votes and the same votes. How to solve the security problem?
 *
* What are the criteria for verifying multithreading security issues?
 *
* 1) check whether the current program is a multithreaded environment
* 2) whether there is shared data {yes tickets
* 3) whether there are multiple statements to operate on shared data
 *
 *
* 1) and 2) must be available: the multithreaded environment is used now, and there is shared data
 *
 *
* start with 3)
* Java provides a synchronization mechanism: include the synchronous code blocks of multiple statements for shared data operations
* format:
* synchronized (lock object) {/ / the same lock that multiple threads must use (any Java class object is allowed)
* operate multiple statements on shared data
 *                          }

Shared resource class
 *
* synchronized: keyword -- implemented in built-in language (jvm to implement locking operation: lock release: automatic release)
* it can be through code blocks (in code) and can be used on methods (synchronous methods)
* synchronized synchronization lock --- it belongs to "pessimistic lock"
* pessimistic lock: when its own thread is executing, other threads cannot enter the synchronization code block, and other threads cannot enter
* modify data to ensure data security! (for frequent write operations)

public class SellTicket implements Runnable {
    public static int tickets = 100 ;//100 tickets

    private Demo demo = new Demo();
   // private Object obj = new Object() ;


    //t1,t2,t3
    @Override
    public void run() {
        //There are always tickets for the simulation
        while(true){
        //t1,t2,t3
            //Add synchronization code block
            //Understand it as: door opening / closing
//            synchronized(new Object()) {/ / three threads have their own lock objects


            //t1 comes in, t2 and t3 have no way to enter
           // Obj / / synchronize object
            //The lock object can be any Java class object
            synchronized(demo){ //A lock object
                if(tickets>0){  //t1 come in
                    //Sleep for 100 milliseconds
                    //To simulate network latency
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+
                            "In the second"+(tickets--)+"Tickets");
                }
            }
        }
    }
}

//Custom class
class Demo{

}

public class SellTicket implements Runnable {

/ / 100 tickets
    public static int tickets = 100 ;

/ / declare a Lock: Lock
    private Lock lock = new ReentrantLock() ;

    @Override
    public void run() {
/ / simulation always has tickets
        while(true){

/ / obtain a lock: a thread must hold a lock when executing to this block
            lock.lock();

/ / after execution, release the lock manually
/ / in development: try catch... Finally: exceptions are caught and throws will not be used
/ / deformation format: try catch... catch...
            //try...finally...
            try{
                if(tickets >0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "selling" + (tickets -- + "ticket");
                }
            }finally {
/ / release resource code block
/ / release the lock
                lock.unlock();
            }

 

1.1 what is a lock?

In computer science, lock or mutex is a synchronization mechanism used to enforce access restrictions on resources in an environment with many execution threads. Locks are designed to enforce mutually exclusive and concurrency control policies.

Locks usually require hardware support to be implemented effectively. This support usually takes the form of one or more atomic instructions, such as "test and set", "fetch and add" or "compare and swap". These instructions allow a single process to test whether the lock is idle, and if so, obtain the lock through a single atomic operation.

1.2. An important attribute of locks is Granularity [gr æ nj ʊ‘ lær ɪ t ɪ]

Before introducing lock granularity, you need to understand three concepts about locks:

1. Lock overhead lock overhead is the time that the lock occupies memory space, cpu initializes and destroys the lock, and acquires and releases the lock. The more locks the program uses, the greater the corresponding lock overhead

2. Lock contention lock contention occurs when a process or thread attempts to acquire a lock held by another process or thread. The smaller the lock granularity, the smaller the possibility of lock competition

3. Deadlock deadlock when each of at least two tasks waits for a lock held by another task, lock granularity measures the amount of data protected by the lock. Generally, coarse-grained locks are selected (the number of locks is small, and each lock protects a large amount of data). The lock overhead is small when a single process accesses the protected data, but the performance is poor when multiple processes access at the same time. Because it increases the competition of locks. On the contrary, the use of fine-grained locks (a large number of locks, each lock protects a small amount of data) increases the cost of locks, but reduces lock competition. Lock granularity, for example, lock field in the database, lock field in the table

Related terms: critical section, mutex / mutual exclusion, semaphore / binary semaphore

2. Types of locks

2.1. Exclusive lock / shared lock

Exclusive lock means that the lock can only be held by one thread at a time. (ReentrantLock, Synchronized)

A shared lock means that the lock can be held by multiple threads. (ReadWriteLock)

Mutex / read / write lock

Exclusive lock / shared lock is a broad term. Mutually exclusive lock / read-write lock correspond to specific implementation respectively. In Java, for example, ReentrantLock is a mutually exclusive lock (exclusive lock), and ReadWriteLock is a read-write lock (shared lock). Exclusive locks and shared locks are also implemented through AQS

Lock upgrade: read lock to write lock (not supported)

Lock degradation: write lock to read lock (supported)

2.2. Readwritelock ReentrantReadWriteLock

The lower 16 bits represent write lock and the higher 16 bits represent read lock
--------
Copyright notice: This article is the original article of CSDN blogger "blackbeilei", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/u010648018/article/details/79750608

      
    

Fair lock / unfair lock

Fair lock means that multiple threads acquire locks in the order in which they apply for locks.

Unfair lock means that the order in which multiple threads acquire locks is not in the order in which they apply for locks. It is possible that the thread that applies later obtains locks first than the thread that applies first. It may cause hunger.

For Java ReentrantLock, specify whether the lock is a fair lock through the constructor. The default is a non fair lock. The advantage of non fair lock is that the throughput is greater than that of fair lock.

For Synchronized, it is also an unfair lock. Unlike ReentrantLock, which acquires locks through AQS control threads, there is no way to turn it into a fair lock.
--------
Copyright notice: This article is the original article of CSDN blogger "blackbeilei", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/u010648018/article/details/79750608

Reentrant lock

Reentrant lock, also known as recursive lock, refers to that when the same thread obtains the lock in the outer method, it will be obtained automatically when entering the inner method

As in the above code, if synchronized is not a reentrant lock, testB will not be executed by the current thread, resulting in a deadlock.

 

It should be noted that the number of times of re-entry lock locking and unlocking should be equal.

C==0 indicates that the lock has not been obtained. Else indicates that the lock has been obtained. At this time, add 1 to the state. Accordingly, each time the lock is released, reduce 1 to the state

2.4. Optimistic lock / pessimistic lock

Optimistic lock / pessimistic lock does not refer to specific types of locks, but from the perspective of concurrency.

Pessimistic locking believes that there are many concurrent update operations. If you do not lock, there will be problems

Optimistic locking believes that there are not many concurrent update operations and locking is not required. The implementation of optimistic lock in database generally adopts version number, and CAS can be used to realize optimistic lock in Java.

2.5. Sectional lock

Sectional lock is a kind of lock design, not a specific lock. For condensenthashmap, efficient concurrent operation is realized through segmented lock.
--------
Copyright notice: This article is the original article of CSDN blogger "blackbeilei", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/u010648018/article/details/79750608

Spin lock

Spin lock means that the thread trying to acquire the lock will not block, but will try to acquire the lock in a circular way. The advantage is to reduce context switching, but the disadvantage is that it always occupies CPU resources.

. deflection lock / lightweight lock / heavyweight lock

This is jdk1 For the optimization of Synchronized locks in 6, first understand the following object header (Mark Word):

Runtime JVM memory layout

Original link: https://blog.csdn.net/u010648018/article/details/79750608


* although syncrhonized can solve the thread safety problem: synchronizing code blocks / synchronization methods, the execution efficiency is low and deadlock may occur
* two or more threads wait for each other!

Solution to deadlock problem: "producer consumer thought" must ensure that multiple threads must use the same resource object!

public class DieLockDemo {

    public static void main(String[] args) {

        //Create resource class object
        DieLock dl1 = new DieLock(true) ;
        DieLock dl2 = new DieLock(false) ;

        //Create thread class object
        Thread t1 = new Thread(dl1) ;
        Thread t2 = new Thread(dl2) ;

        //Start thread
        t1.start();
        t2.start();
        /**
         *   if(flag){
         *             synchronized (MyDieLock.objA){
         *                 System.out.println("if objA");
         *                 synchronized (MyDieLock.objB){
         *                     System.out.println("if objB"); //You need to wait for the second thread objB to release the lock
         *                 }
         *             }
         *         }else{
         *             synchronized (MyDieLock.objB){
         *                 System.out.println("else objB");
         *                 synchronized (MyDieLock.objA){
         *                     System.out.println("else objA");//You need to wait for the first thread to release the objA lock
         *                 }
         *             }
         *         }
         *
         *
         * Case 1:
         * if objA
         * else objB
         *
         * When the first ObjA lock is used, "if objA" is output
         * At the same time, the second thread dl2: ObjB lock is used "else objB"
         *
         *
         * Case 2:
         * else objB
         * if objA
         *
         *
         * Scenario 3: ideal scenario:
         * if objA
         *      if objB
         *  else objB
         *      else objA
         */
    }
}
public class MyDieLock {

    //Create two lock objects (static instance variables)
    public static final Object objA = new Object() ;
    public static final Object objB = new Object() ;
}

Test class
* SetThread: production data
* GetThread: consumption data
* Student: Student data
 *
 *
* problem 1: Data null--0:
 *
* in production resource class and consumer resource class: new Student(): not the same object
 *
 *
 *
* simulation always has data: add loop operation while(true)
 *
* question 2: name and age do not match
* the execution of threads is random, resulting in unsafe multithreaded programs
 *
 *
* What are the criteria for verifying multithreading security issues?
* 1) check whether it is a multithreaded environment
* 2) is there shared data
* 3) are there multiple statements to operate on shared data
 *
 *
* 3) improvement: use synchronous code block to include!
 *
 *
 *
* question 3: when students output data, they print a lot at one time
* a little time slice of the thread: enough for the current thread to execute many times!
 *
* Optimization:
* when you don't need to output student data, you can output a lot at one time, but in turn
* "GaoYuanYuan" 41
* "Yang Decai" 27

public class ThreadDemo {

    public static void main(String[] args) {

        Student s = new Student() ; //Same resource class object
        //Create production resource class object
        SetThread st = new SetThread(s) ;
        //Create consumer resource class object
        GetThread gt = new GetThread(s) ;

//        Create thread class object
        Thread sThread = new Thread(st) ;
        Thread gThread = new Thread(gt) ;

        //start-up
        sThread.start();
        gThread.start();

    }
}
@Version 1.0
 * Producer resources
 */
public class SetThread implements  Runnable {

    private Student s ;
    public SetThread(Student s){
        this.s =  s ;
    }

    //Statistical variables
    int x = 0 ;
    @Override
    public void run() {

        //Continuously generate data
        while(true){

            synchronized (s){
                //Judge if the producer has data
                if(s.flag){
                    try {
                        //The producer has data and needs to wait for the consumer thread to use it
                        s.wait(); //The lock object is calling wait()
                        //wait(): whether to lock the current lock object immediately when calling the method
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //Currently, before executing the following code: the execution qualification of the thread is by the consumer thread where GetThread is located
                if(x % 2 == 0){
                    s.name  = "Gao Yuanyuan" ;
                    s.age = 41 ;

                }else{
                    s.name = "Yang Decai" ;
                    s.age = 27 ;
                }
                x ++ ;


                //Change tag
                s.flag = true ;
                //Notify the other thread: use the data quickly
                s.notify(); //Wake up method called by lock object


            }

        }
       // Student s = new Student();

    }
} 
Consumer resources
public class GetThread implements Runnable {

    private Student s ;
    public GetThread(Student s){
        this.s = s ;
    }

    @Override
    public void run() {

        //Simulated consumption data
        while(true){

            synchronized (s){
                if(!s.flag){
                    //If the consumer has no data, it needs to wait for the production thread to generate data
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(s.name+"---"+s.age);

                //Change tag
                s.flag = false ;//No data
                //Notify the opposite thread: Production thread: generate data
                s.notify() ;

            }

        }


       // Student s = new Student() ;

    }
}
public class Student {

    String name ;
    int age ;

    //Is there a student data tag
    boolean flag ; //true has data, false has no data

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

1. There are several ways to create multithreading
Three kinds
1) inheritance relationship:
Customize a class to inherit from Thread class
Override the run method of the Thread class
Create the current class object in main, and start the thread to call start()
2) implement Runnable interface
Customize a class to implement the Runnable interface
Override the run method of the Runnable interface
Use the custom class as a resource sharing class in main - create the current class object
Create a Thread class Thread class object and pass the resource sharing class as a parameter
Start the thread separately and call start()
            
3) thread pool

2. How many ways can I get the bytecode file of a class?
Three kinds
1) getClass() method of object class
2) class attribute of any Java type
3) reflection: class Forname ("package name. Class name");

3. Difference between wait method and sleep method (often)
1) whether the lock is released
When the lock object calls the wait method, release the lock immediately;
sleep(xx): when called, the thread is always blocked and will not release the lock
    
2) different sources
wait() comes from the Object class ----- > relationship with the lock Object!
Why wait(): thread waiting; The notify() notifyAll() thread wakes up and defines "notify" in the Object class?
Because these methods are related to locks, and the lock object can be any Java object!
sleep(): it comes from the Thread class ---- > which belongs to a state and has nothing to do with locks
    
3) they will throw interruptedException: if the current state is interrupted, they will throw an exception!

4. How many thread states are there?
6 medium
Thread class enumeration class State
            NEW
            RUNNABLE
            BLOCKED
            WAITTING
            TIMED_WAITTING
            TERMINATED

5. What is a static agent? Please describe
Static proxy: proxy classes and real roles need to implement the same interface
Agent class: help real roles to enhance business functions
Real role: focus on your own things
                    
/ / proxy role
Thread class implements Runnable{
                    
                            private Runnable target ;
                            
                            public void run(){
                                if(target!=null){
                                    target .run() ;
                                }
                            }
                    }
/ / real role
                    MyRunnable implements Runnable{
/ / business logic: complete the preemption of CPU execution rights (data) by multiple threads in the process of concurrent execution
                        public void run(){
                            ...
                        }
                    }

6. How to solve thread safety problems?
Synchronization mechanism: pessimistic lock (synchronized)
Use synchronization code to solve thread safety problems: with synchronization lock, other threads cannot change its data (for frequent write operations)
Synchronized (lock object){
Multiple statements operate on shared data;
                }
                
Synchronization method
public synchronized return value type method name (formal parameter list) {/ / lock object: this
                    ...
                }
        
Mybatis framework - > mybatis plus (plug-ins can use optimistic locks)
                                                                


7. What is the waiting wake-up mechanism in Java?

The waiting mechanism is called "wake-up notification"
Currently, multiple threads have circular waiting ----- deadlock
Use notify() notifyAll() to wake up the thread in the blocking state to operate business data!
Multiple threads must use the same resource object!

Creative design patterns: creation of objects
* Java provides: simple factory mode - static factory method mode
* advantages: you do not need to create a specific instance of a specific class, but through the factory class
 *
* disadvantages: once a new type is added, modify the factory class!
 *
* a factory class needs to be provided to be responsible for the creation of specific instances

public class Test {

    public static void main(String[] args) {

        //Create cat
        Cat cat = new Cat() ;
        cat.eat();
        cat.sleep();
        //dog
        Dog dog = new Dog() ;
        dog.eat();
        dog.sleep();

        System.out.println("------------------------");

        //Provide factory classes to create specific animal instances
       /* Cat c1 = AnimalFactory.createCat();
        c1.eat();
        c1.sleep();
        Dog d = AnimalFactory.createDog() ;
        d.eat();
        d.sleep();*/

       //After optimization
        Animal animal = AnimalFactory.createAnimal("dog"); //A parent class reference points to a child class object
        animal.eat();
        animal.sleep();
        animal = AnimalFactory.createAnimal("cat") ;
        animal.eat();
        animal.sleep();
    }

}
public class Animal {

    public void eat(){
        System.out.println("Animals need to eat");
    }
    public void sleep(){
        System.out.println("Animals need rest");
    }
}
public class AnimalFactory {
    //Privatization of construction methods
    private AnimalFactory(){ //The current class object cannot be created

    }

    //Static method
    //Create an instance of a cat
 /*   public static Cat createCat(){

        return new Cat() ;
    }

    //Create an instance of the dog
    public static Dog createDog(){
        return new Dog() ;
    }




    //Create an instance of a pig
    public static Pig createPig(){
        return new Pig() ;
    }*/

 //Optimization: use polymorphism: provide function expansion
    public static Animal createAnimal(String type){
        if(type.equals("dog")){
            return new Dog() ;
        }else if(type.equals("cat")){
            return new Cat() ;
        }else if(type.equals("pig")){
            return new Pig() ;
        }else{
            System.out.println("I'm sorry,The factory class has no instance creation of the provider animal!");
        }
        return null ;
    }

}
public class Cat extends  Animal {


        public void eat(){
            System.out.println("i can eat and eat mouse");
        }

        public void sleep(){
            System.out.println("i can sleep ...");
        }

}
public class Dog  extends  Animal{

    public void eat(){
        System.out.println("i can eat and eat meat");
    }
    public void sleep() {
        System.out.println("i can sleep");
    }

}

Factory method mode:
 *
* object creation: there is an interface to complete
* sub implementation class of interface ----- > factory class for creating specific instances
 *
* advantages: interface oriented programming: the structure is very clear and easy to maintain
 *
* disadvantages: the amount of code increases and additional factory classes need to be written

public class Test {
    public static void main(String[] args) {

        //Factory method mode is not used
        //Abstract class polymorphism
        Animal a = new Cat();
        a.eat();
        a = new Dog() ;
        a.eat();

        System.out.println("-----------------------------------");

        //Cat factory class
        Factory f = new CatFactory() ;
        Animal animal = f.createAnimal(); //new Cat()
        animal.eat();


        f = new DogFactoy() ;
        Animal an = f.createAnimal();
        an.eat();

    }
}
public interface Factory { //Factory interface


    //Create an instance of an animal
    public abstract Animal  createAnimal() ;
}
public class DogFactoy implements Factory {

    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}
public  abstract  class Animal {

    public abstract  void eat() ;//eat
}
public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cats eat fish");
    }
}

A single example of creative design pattern
 *
* single example:
* when loading a class, there is always only one object in memory! (this type of object is created automatically)
 *
* two types:
* starving Han style: features: single case mode that will never cause problems!
* when loading this class, an object has been created in memory!
* 1) customize a class (specific class)
* 2) member location: create an instance of the current class
* 3) provide a private construction method: it cannot be created by the outside world
* 4) provide public access methods: static, return value the current class itself
 *
* lazy: Singleton mode with possible problems
* 1) customize a class (specific class)
* 2) member location: variable of declaration type
* 3) privatization of construction method
* 4) provide public access methods:
* need to judge: if there is no object at present, the new object
 *
* lazy loading or delayed loading exists!
* possible multithreading security issues:
 *
* how
* add synchronous lock

public class Tests {

    public static void main(String[] args) {
        /*Student s  =new Student() ;
        Student s2 = new Student() ;
        System.out.println(s==s2) ;//false
        System.out.println(s.getClass()==s2.getClass());//true*/
        //Getclass() --- > class package name Class name

       // Student.s = null ; // Changed by the outside world

        Student s1 = Student.getStudent();
        Student s2 = Student.getStudent();
        System.out.println(s1==s2);

        System.out.println("-----------------");
        Programmer p1 = Programmer.getPro();
        Programmer p2 = Programmer.getPro();
        Programmer p3 = Programmer.getPro();

        System.out.println(p1==p2);
        System.out.println(p1==p3);

    }
}

 * Hungry Chinese style of standard singleton mode:Runtime
 * individual Java Every application has one Runtime Class instance, which enables the application to connect with its running environment
 */
public class RuntTimeDemo {

    public static void main(String[] args) throws IOException {

        Runtime runtime = Runtime.getRuntime();
      //  Runtime runtime2 = Runtime.getRuntime();
        //System.out.println(runtime==runtime2);
        int cpuSize = runtime.availableProcessors();
        System.out.println(cpuSize);
        runtime.exec("notepad") ;
        runtime.exec("mspaint") ;
        runtime.exec("calc") ;
    }
}
public class Student {

    //Create an instance of this class -- - (instance variable of the class)
//    public static Student s = new Student() ;
    private static Student s = new Student() ;
    private Student(){} //Cannot create object

    //Provide external public access methods: static
    public static Student getStudent(){
        return s ;
    }
}

public class Programmer {

    private static Programmer pro = null ;

    private Programmer(){}


    //p1,p2,p3
    //External public access method
    /*public static Programmer getPro(){
        synchronized (Programmer.class){
            if(pro ==null){
                pro = new Programmer() ;
            }
            return pro ;
        }

    }*/
    public synchronized static Programmer getPro(){//Static synchronization method: lock object: current class name Class attribute
            if(pro ==null){
                pro = new Programmer() ;
            }
            return pro ;

    }


}

Tortoise and rabbit race
 *
 *
* runway --- as a resource

public class Race  implements Runnable{

    //When class 1 is loaded, static variables are defined
    //winner
    private  static String winner = null ;

    //Both rabbits and turtles have to perform this run
    @Override
    public void run() {

        //for loop: indicates 1-100 steps
        for(int x = 1 ; x <= 100 ; x ++){

            //In the real story: the rabbit wants to sleep. Simulate the rabbit to sleep
            if(Thread.currentThread().getName().equals("rabbit") && (x % 10 ==0 )){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //Define a way to define the end of the game
            boolean flag = gameOver(x) ;
            if(flag){
                break ;
            }
            System.out.println(Thread.currentThread().getName()+"Run away====>"+x+"step");

        }

    }

    //How to end the game
    private boolean gameOver(int step) {//Steps x
        //Case 1: if the current winner is not equal to null, there is a winner and the game is over
        if(winner!=null){
            return true ;
        }{
           //Case 2: judge that if the current step > = 100, the game will end
            if(step>=100){
                winner = Thread.currentThread().getName() ;
                System.out.println("winner is:"+winner);
                return true ;
            }
        }
        return false ;
    }


    //User thread
    public static void main(String[] args) {

        //Create a resource sharing class
        Race race = new Race() ;
        //Create thread class object
        Thread t1 = new Thread(race,"rabbit") ;
        Thread t2 = new Thread(race,"tortoise") ;


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

    }
}

Thread group ThreadGroup thread group represents a collection of threads
 *
* methods in Thread class:
* public final ThreadGroup getThreadGroup(): get the default thread group of all current threads
 * ThreadGroup
* public final String getName(): get the default thread group name: (the default is main)
 *
 *
* construction method:
* ThreadGroup(String name): construct a thread group with a new name
 *
* the default thread group of all threads is main thread (user thread)

public class ThreadGroupDemo {
    public static void main(String[] args) {
        //method() ;
        method2() ;
    }

    //Set thread group name
    private static void method2() {
//        ThreadGroup(String name): construct a thread group with a new name
          ThreadGroup tg = new ThreadGroup("myMain") ;
          //Create thread class object: thread group object can be passed as a parameter
        //public Thread(ThreadGroup group,String name)
        Thread t1 = new Thread(tg,"Thread 1") ;
        Thread t2 = new Thread(tg,"Thread 2") ;


        System.out.println(t1.getThreadGroup().getName());
        System.out.println(t2.getThreadGroup().getName());


    }

    private static void method() {
        //Create two thread class objects

        MyThread my1 = new MyThread() ;
        MyThread my2 = new MyThread() ;

        //Get the corresponding thread group name
        ThreadGroup tg1 = my1.getThreadGroup();
        String name = tg1.getName();
        ThreadGroup tg2 = my2.getThreadGroup();
        String name2 = tg2.getName();
        System.out.println(name);
        System.out.println(name2);
    }
}

Use of thread pool:
* 1) interface: ExecutorService: track one or more asynchronous tasks
* 2) how to instantiate ---- > executors Newfixedthreadpool (int) factory method:
 *
* Executors: factory class
* provides methods for creating thread pool objects
 *              public static ExecutorService newFixedThreadPool(int nThreads)
 *
 *  ExecutorService
* method:
 *                  Future<?> Submit (runnable task): submit asynchronous tasks through the thread pool
* < T > Future < T > submit (callable < T > task): submit asynchronous tasks
 *
* Future: the result of asynchronous task calculation!
 *
 *
* the third way: thread pool implementation ----- > or customize a class to implement Runnable interface

public class ThreadDemo {
    public static void main(String[] args) {


       /* new Thread(){
            @Override
            public void run() {

            }
        }.start();*/
        //Create a thread pool: static factory mode
        ExecutorService pool = Executors.newFixedThreadPool(2);

        //Submit asynchronous task
        // Future<?>  Submit (runnable task): submit asynchronous tasks through the thread pool
       /* pool.submit(new MyRunnable()) ;
        pool.submit(new MyRunnable()) ;*/
       //Callable is better than Runnable interface
        //You can track specific exception errors (if an exception occurs in the thread during execution, you can track the exception information!)
       pool.submit(new MyCallable()) ;
       pool.submit(new MyCallable()) ;

        //After the threads in the bottom thread pool are used, they will be returned to the bottom thread pool
        pool.shutdown();

    }
}

j ava.util.Timer: timer: a thread arranges the execution of the task once, or repeats it regularly.
* construction method:
* public Timer() parameterless construction method
 *
* membership method
*public void cancel(): cancels the timer
*public void schedule(TimerTask task,Date time): execute this task within the specified date and time
*Public void schedule (TimerTask, long delay): execute the task after the specified delay time (time: ms)
 *
 *            public void schedule(TimerTask task,
 *                      long delay,
* long period): repeat the interval period after the specified delay time to execute the task task
 *
* demand:
* at 18 o'clock on a certain day, all the suffixes in the d://demo folder are java file deleted! (Timer+io stream + recursion: comprehensive use)
 *
 *
 *
* Java design principles:
* single responsibility
* interface separation
* opening and closing principle
* dependency injection principle (depends on abstract classes or interfaces, not on concrete class implementations)

public class TimerDemo {

    public static void main(String[] args) {
        //Create a timer
        Timer timer  = new Timer() ;
        //   public void cancel(): cancels the timer

        //Parameter 1: scheduled task: abstract class, defining subclasses that inherit from TimerTask
       // timer. schedule(new MyTask(timer),3000); : Perform this task once in 3 seconds

      /*  public void schedule(TimerTask task,
                     long delay,
                       long period) :Start repeating the interval period after the specified delay time to execute the task task task*/

      timer.schedule(new MyTask(timer),2000,3000);
    }
}

//Scheduled task
class MyTask extends TimerTask{ //TimerTask implements the Runnable interface -- it will use the synchronization mechanism
    private Timer t ;
    public MyTask(Timer t){
        this.t = t ;
    }

    @Override
    public void run() {

        System.out.println("bom...");
        //off timer 
        //t.cancel() ;

    }
}

1. There are several ways to create multithreading. List them
            
1) inherit from the Thread class, rewrite the run method, and then create the current class object to start the Thread
2) implement the Runnable interface, rewrite the run method, pass the current resource class as a parameter to the Thread class, and then start the Thread
    
                new Thread(new Runnable(){
                        public void run(){
                            ...
                        }
                
                }).start ;
3) thread pool
Factory class: Executors
                        public static ExecutorService newFixedThreadPool(int nThreads)
                        
Through its child implementation object: ThreadPoolExecutor
7 parameters:
                                            
                                            corePoolSize
                                            maxmiumPoolSize
handler: Auto enable reject policy
TimeUnit: timer
ThreadFactory --- create a new thread object
                                                    DefaultThreadFactory
keepAliveTime: save survival time
BlockingQueue (Collection)
                ExecutorService
Future submit (callable < E > call): submit asynchronous tasks
2. What is singleton mode? Please list two cases
When creating objects, always ensure that there is only one object in memory!
Singleton mode:
Starving Han style: there will be no safe singleton mode: Runtime
As soon as the current class is loaded, an object is created (only this object)
1) the current class is a concrete class
2) class member location: create the current static instance variable and privatize it
3) privatization of nonparametric construction method
4) provide external public access methods: static methods, and the return value is the current class itself
            
            
            public class Student{
                private static Student s = new Student() ;
                
                private Student(){}
                
                public static Student getStudent(){
                    return s ; 
                }
            }
            
Lazy: Singleton mode with possible security problems (in actual development: lazy loading / delayed loading!)
1) the current class is a concrete class
2) a current class object will not be created immediately: instead, member variables of the current type will be declared
3) privatization of nonparametric construction method
4) provide external static public access methods: the return value is also the current class itself
First judge whether there is a class object at present. If it is null, create a new object
Returns the current class object;
                        
            class Teacher{
                private static Teacher t = null ;
                private Teacher(){}
                
                
/ / t objects are shared
/ / concurrent threads accessing public variables: conflicts will occur
                
/ / use synchronization mechanism: synchronized
                public synchronized static Teacher getTeacher(){
if(t==null) {/ / create an object only when it needs to be used!
                        t = new Teacher() ; // Create a new object
                    }
                    
                    return t ;
                }
                
            }        
                    
                    
                    Teacher t1 = Teacher.getTeacher() ;
                    Teacher t2 = Teacher.getTeacher() ;
        

3. What is a simple factory and factory method model
Simple factory: static factory method pattern
Advantages: the new concrete class is not required, but the factory class is required
Responsibility of factory class: it is responsible for the creation of specific class objects!
Disadvantages:
When new types are added, the factory class code needs to be modified frequently! (polymorphism can be used!)
                    
Factory method:
A factory interface is required. The return value of the method in the factory interface is an abstract type
Abstract classes also need to have specific subclasses, and the creation of specific class objects: the subclasses of factory interfaces (factory classes of specific classes)
                    
                    interface Factory{
                        public abstract Animal  createAnimal() ;
                    }
                    
/ / factory class of dog
                    class DogFactory implements Factory(){
                        public Animal createAnimal(){
                            return new Dog() ;
                        }
                    }
                    
                    
                    
Advantages: interface oriented programming and the use of interface polymorphism provide functional scalability
Disadvantages: large amount of code: a new type is added, and the factory class needs to be provided
                    
                    
            

4. The difference between set and array

Length difference
Sets: variable
Arrays: fixed
Storage element
Collection: can store elements of any type: reference type
Array: it can store both reference types and basic types (element types must be unified)
    
Difference between stored data types
Array: data type: must be uniform
Collection: only reference types

5. What is the synchronization mechanism of multithreading
            
Solution:
Accessing conflicting variables for public variables in concurrent threads
                    
Synchronization mechanism: Four
1) ThreadLocal ----- > database Connection pool will be used! (create Connection: Connection object)
2) synchronized code block / synchronization method
3)wait() or notify()
                    4)volatile

MES system

URL s are subsets of URI s

URI
        /dianshang/login
Specific access path specified by URI:
Agreement
ftp protocol
Thunder agreement
Mail protocol
            jdbc:
http protocol

URL:
Network protocol: http/ https: encryption protocol is more secure
        http://www.baidu.com:80/index.html
        
        http://localhost:8080/dianshang/login

 

 *

Added by husslela03 on Tue, 08 Feb 2022 00:25:16 +0200