Java Basic Review (V)

Keywords: socket Java network JDK

The review notes are based on the JavaSE notes of the 27 employment classes of the Intelligence Podcast. Link: Link: https://pan.baidu.com/s/1boDix6R Password: r1p6, I recommend that you don't read the new white, because it involves too many details, but it makes you easy to give up the path of Java. The new white recommends the following set of videos: Teacher Han Shunping's Java Basic Link: https://pan.baidu.com/s/1o8jVLLS Password: axfj

The blogger declared: I am not a clever podcaster, but a rookie. Now I am filling the Java foundation, and I have developed a set of Java videos and Android videos of clever podcasts. So these words may appear in my notes. Please shut up your mouth.

Multithreading (Mastery)

  • 1. What is a thread?
    • Threads are a path to program execution, and a process can contain multiple threads.
    • Multi-threaded concurrent execution can improve the efficiency of the program, and can accomplish many tasks at the same time.

Java Multithread Understanding: Processes, threads, parallelism, concurrency in Java multithreading - the beauty I yearn for - blog Park

Differences between multithreaded parallelism and concurrency (Understanding)

  • Parallel operation means that two tasks are running simultaneously, that is, task A and task B are running at the same time. (Multi-core CPU is required)
  • Concurrent means that both tasks are requested to run, and the processor can only take one task and arrange the two tasks in turn. Because of the short time interval, it makes people feel that both tasks are running.
  • For example, I chat with two netizens, one computer with my left hand to chat with A, and the other computer with my right hand to chat with B. This is called parallel.
  • If I use a computer, I will send a message to A first, then to B immediately, and then to A, and then to B. This is called concurrency.

Are the principles of Java programming and JVM startup multithreaded?

  • A: Running Principles of Java Programs

    • The Java command will start the Java virtual machine and JVM, which is equivalent to starting an application, that is, a process. The process automatically starts a "main thread" and then the main thread calls the main method of a class.
  • B: Is the startup of JVM multithreaded?

    • The JVM startup starts at least the garbage collection thread and the main thread, so it is multithreaded.

Multithread Programming Method 1 (Mastery)

  • 1. Inherit Thread
    • Define Class Inheritance Thread
    • Rewriting run Method
    • Write what the new thread does in the run method
    • Creating Thread Objects
    • Open a new thread, and the run method is automatically executed internally
public class Demo2_Thread {

    public static void main(String[] args) {
        // 4. Create subclass objects of the Thread class
        MyThread mt = new MyThread();
        // 5. Open threads
        mt.start();
        // This is not a way to open a sub-thread, but to call the run method of this class in the main thread.
        // mt.run();

        for (int i = 0; i < 1000; i++) {
            System.out.println("bb");
        }
    }

}

// 1. Inherit Thread
class MyThread extends Thread {
    // 2. Rewriting run Method
    public void run() {
        // 3. Write the code to be executed in the run method
        for (int i = 0; i < 1000; i++) {
            System.out.println("aaaaaaaaaaaa");
        }
    }
}

Multithread Programming Method 2 (Mastery)

  • 2. Implementing Runnable
    • Define Class to Implement Runnable Interface
    • Implementation of run method
    • Write what the new thread does in the run method
    • Create custom Runable subclass objects
    • Create the Thread object and pass it in to Runnable
    • Invoking start() to open a new thread automatically calls Runnable's run() method internally
public class Demo3_Thread {

    public static void main(String[] args) {
        //4. Create subclass objects of Runnable
        MyRunnable mr = new MyRunnable();   
        //Runnable target = mr; mr = 0x0011
        //5. Pass it as a parameter to Thread's constructor
        Thread t = new Thread(mr);
        //6. Open threads
        t.start();                          

        for(int i = 0; i < 1000; i++) {
            System.out.println("bb");
        }
    }

}

//1. Define a class to implement Runnable
class MyRunnable implements Runnable {      
    //2. Rewriting run Method
    @Override
    public void run() {         
        //3. Write the code to be executed in the run method
        for(int i = 0; i < 1000; i++) {     
            System.out.println("aaaaaaaaaaaa");
        }
    }

}

Principle of Runnable Implementation (Understanding)

  • View source code
    • 1. Look at the constructor of the Thread class, passing a reference to the Runnable interface.
    • 2. Find the target assignment of the passed target to the member variable by the init() method
    • 3. Look at the run method and find that there is a judgment in the run method. If the target is not null, the run method of the Runnable interface subclass object will be called.

The difference between the two ways (mastery)

  • Look at the differences in source code:
    • a. Inheritance of Thread: Since the subclass overrides the run() of the Thread class, when the start() is called, it looks directly for the run() method of the subclass.
    • b. Implementing Runnable: A reference to Runnable is passed into the constructor, and member variables remember it. When starting () calls run(), the reference to member variable Runnable is internally judged to be empty. When compiling for empty, Runnable's run() is not looked at, and run() method of subclass is executed at runtime.
  • Inheritance of Thread
    • The advantage is that the method in the Thread class can be used directly, and the code is simple.
    • The disadvantage is that if you already have a parent class, you can't use this method.
  • Implementing Runnable Interface
    • The advantage is that it doesn't matter if the thread class defined by itself has a parent class, because the parent class can also implement the interface, and the interface can be implemented more.
    • The disadvantage is that the method in Thread can not be used directly. Thread method can only be obtained after the thread object is acquired. The code is complex.

Thread method

  • Get the name and set the name
    • 1. Get a name
    • Get the name of the thread object through the getName() method
    • 2. Setting the name
    • The name of the String type can be passed in through the constructor
    • Thread object names can be set by setName(String) method
  • Get the object of the current thread
    • Thread. current Thread (), which can also be retrieved by the main thread
  • Sleeping threads
  • Thread. sleep (milliseconds, nanoseconds), which controls how many milliseconds the current thread sleeps
    • 1 second = 1000 milliseconds
    • 1 second = 1000 * 1000 * 1000 nanoseconds (Win system is not very good for this support, it is recommended not to use better)
  • Daemon thread
    • Daemon threads are a bit of a type of chess cart and horse guns. When the general kneels, the daemon threads kneel.
    • setDaemon(), which sets a thread as a daemon thread, which will not execute independently. When all other non-daemon threads are executed, they will exit automatically. The method set to true means that they are daemon threads.
  • Join threads
    • join(), the current thread pauses, waiting for the specified thread to finish execution, the current thread continues (personal feeling should be when a small clerk is driving a bus, the leader wants to drive, the small clerk immediately returns to the leader to drive, the leader finished driving and then gives you to drive)
    • join(int) can wait for the specified milliseconds to continue.
  • Comity Threads (Understanding)
    • yield gives up cpu, an effect that is virtually impossible to achieve
  • Setting Thread Priority (Understanding)
    • setPriority() sets the priority of threads (range 1-10, default 5), which is not obvious, just as an understanding.

synchronization

  • Synchronized code block (master)
    • 1. Under what circumstances synchronization is required
      • When multiple threads are concurrent and multiple pieces of code are executed simultaneously, we hope that the CPU will not switch to other threads during the execution of one piece of code. Synchronization is needed at this time.
      • If the two pieces of code are synchronized, then only one piece of code can be executed at the same time, and no other piece of code will be executed until the end of one piece of code.
    • 2. Synchronized code block
      • Use the synchronized keyword plus a lock object to define a piece of code, which is called a synchronized block of code.
      • Multiple synchronous blocks of code are synchronized if they use the same lock Object (lock Object can be arbitrary, Object object Object can be), then they are synchronized.
      • Lock objects cannot be anonymous because anonymous objects are not the same object
  • 3. Synchronization method (mastery)
    • Modify a method with synchronized keywords, in which all code is synchronized
    • The lock object of the non-static synchronous method is this, and the lock object of the static synchronous method is the bytecode object of the class (class name. class), not the class name.
  • 4. Thread Safety (Mastery)
    • Thread security issues may arise when multiple threads operate concurrently on the same data
    • Synchronization technology can solve this problem by synchronizing the code of operation data without multiple threads working together.
  • 5. Deadlock (Understanding)
    • When multithreaded synchronization occurs, if the synchronization code is nested and the same lock is used, deadlock may occur (try not to use nested code in development).

Previous thread-safe class reviews (mastery)

  • A: Review the thread security issues mentioned earlier
    • Look at the source code: Vector, String Buffer, Hashtable, Collections. synchroinzed (xxxx)
    • Vector is thread-safe, ArrayList is thread-insecure
    • StringBuffer is thread-safe, StringBuilder is thread-insecure
    • Hashtable is thread-safe, HashMap is thread-insecure
    • Collections. synchroinzed (xxxx) can convert thread-incomplete to thread-safe

Singleton Design Patterns (Mastery)

  • Singleton design pattern: Ensure that the class has only one object in memory.

  • How to ensure that a class has only one object in memory?

    • (1) Control the creation of classes and do not allow other classes to create objects of this class. private
    • (2) Define an object of this class in this class. Singleton s;
    • (3) Provide public access. public static Singleton getInstance(){return s}
  • There are two ways to write a singleton:
    • (1) Hungry Chinese style development uses this way.
//Hungry Chinese Style
class Singleton {
    //1. Private constructor, which other classes can't access
    private Singleton(){}
    //2. Create this class of objects
    private static Singleton s = new Singleton();//Membership variables are private and cannot be called by class name.
    //3. Providing public access to the outside world
    public static Singleton getInstance() {             //Get an instance
        return s;
    }
}
  • (2) Lazy interview writing this way. Multithreading can cause problems
//Lazy Man (Single Delayed Loading Mode)
class Singleton {
    //1. Private constructor, which other classes can't access
    private Singleton(){}
    //2. Declare a reference
    private static Singleton s ;
    //3. Providing public access to the outside world
    public static Singleton getInstance() {             //Get an instance
        if(s == null) {
            //Thread 1 waits, thread 2 waits
            s = new Singleton();//This can lead to the creation of two objects, which is not worth it.
        }

        return s;
    }
}
  • The difference between the hungry and the lazy

    • 1. Hungry Chinese style is space for time (creating objects on the way up, although it consumes memory, but saves time), lazy Chinese style is time for space (every time you come up, you have to make a judgment whether it is empty, wasting time).
    • 2. In multithreaded access, hungry Chinese may not create multiple objects, while lazy Chinese may create multiple objects.

      • (3) final (this pattern is not yet named, not as well known as the two above)
class Singleton {
    //1. Private constructor, which other classes can't access
    private Singleton(){}
    //2. final means final. Variables modified by final cannot be changed.
    public static final Singleton s = new Singleton();

}
Communication between multithreads
Communication between two threads
  • 1. When do you need to communicate?
    • When multiple threads are executed concurrently, by default the CPU switches threads randomly
    • If we want them to execute regularly, we can use communication, such as printing once per thread.
  • 2. How to communicate
    • If you want the thread to wait, call wait()
    • If you want to wake up the waiting thread, call notify();
    • These two methods must be executed in synchronous code and invoked using synchronous lock objects
Thread communication between three or more threads
  • The problem of multi-threaded communication
    • notify() method is to wake up a thread at random
    • NotfyAll () method is to wake up all threads (but every time wake up all bad, after all, some do not meet the conditions, it is recommended to use mutex)
    • JDK5 could not wake up a specified thread before
    • If multiple threads communicate with each other, notify all () is used to notify all threads and while is used to judge the condition repeatedly.
      • Where the if statement waits, it gets up; while loops are circular judgments, and each time the tag is judged
  • New features of JDK 1.5 Mutex Lock (Mastery)
  • 1. Synchronization
    • Synchronization using the lock() and unlock() methods of the ReentrantLock class
    • In fact, this class is designed to replace synchronized.
  • 2. Communication
    • Condition objects can be obtained using the new Condition () method of the ReentrantLock class
    • Use Condition's await() method when you need to wait (call whoever wants to sleep), signal() method when you wake up (call whoever wants to wake up)
    • Different threads use different conditions so that they can distinguish which thread to look for when waking up
Notes for communication between threads:
  • 1. In a synchronous block of code, the wait method is invoked with which object to lock.
  • 2. Why are wait methods and notify methods defined in Object s?
    • Because the lock object can be any object and Object is the base class of all classes, the wait method and notify method need to be defined in the class Object.
  • 3. The difference between sleep method and wait method?
    • a,sleep method must pass in parameters, parameters are time, time to wake up automatically
      The wait method can either pass in parameters or not. The incoming parameters are waiting after the end of the time of the parameters and directly waiting without the incoming parameters.
    • B. Sleep method in synchronization function or block of synchronization code, does not release the lock and sleeps with the lock when sleeping
      The wait method releases the lock in a synchronization function or block of synchronization code

Overview and Use of Thread Groups (Understanding)

  • A: Overview of Thread Groups
    • ThreadGroup is used to represent thread groups in Java. It can classify and manage a batch of threads. Java allows programs to control thread groups directly.
    • By default, all threads belong to the main thread group.
      • public final ThreadGroup getThreadGroup()// Gets the group he belongs to through the thread object
      • public final String getName()// / Gets the name of another group through the thread group object
    • We can also group threads
      • 1. ThreadGroup (String name) creates a thread group object and assigns it a name
      • 2. Create Thread objects
      • 3,Thread(ThreadGroup?group, Runnable?target, String?name)
      • 4. Set priority or daemon threads for the whole group



Case demonstration
1. Use of thread groups, default is the main thread group

        MyRunnable mr = new MyRunnable();
        Thread t1 = new Thread(mr, "Zhang San");
        Thread t2 = new Thread(mr, "Li Si");
        //Getting Thread Groups
        // The method in the thread class: public final ThreadGroup getThreadGroup()
        ThreadGroup tg1 = t1.getThreadGroup();
        ThreadGroup tg2 = t2.getThreadGroup();
        // The method in the thread group: public final String getName()
        String name1 = tg1.getName();
        String name2 = tg2.getName();
        System.out.println(name1);
        System.out.println(name2);
        // From the results, we know that threads belong to the main thread group by default.
        // Through the following tests, you should be able to see that all threads belong to the same group in silence.
        System.out.println(Thread.currentThread().getThreadGroup().getName());

2. Setting Thread Groups by Yourself

        // ThreadGroup(String name)
        ThreadGroup tg = new ThreadGroup("This is a new group.");

        MyRunnable mr = new MyRunnable();
        // Thread(ThreadGroup group, Runnable target, String name)
        Thread t1 = new Thread(tg, mr, "Zhang San");
        Thread t2 = new Thread(tg, mr, "Li Si");

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

        //Setting background threads by group name indicates that all threads in this group are background threads
        tg.setDaemon(true);

3. MyRunnable code:

class MyRunnable implements Runnable {

    @Override
    public void run() {
        for(int i = 0; i < 1000; i++) {
            System.out.println(Thread.currentThread().getName() + "...." + i);
        }
    }

}

Five states of threads (mastery)

  • look and say

    stop() is out of date

  • New, Ready, Running, Blocking, Death

Overview and Use of Thread Pools (Understanding)

  • A: Overview of Thread Pool
    • Starting a new thread is expensive because it involves interacting with the operating system. The use of thread pools can improve performance very well, especially when creating a large number of threads with very short lifetime in the program, we should consider using thread pools. After each thread code in the thread pool is finished, it will not die, but will return to the thread pool and become idle again, waiting for the next object to use. Before JDK5, we had to implement our own thread pool manually. Starting with JDK5, Java has built-in thread pool support.
  • B: Overview of the use of built-in thread pools
    • JDK5 adds an Executors factory class to generate thread pools in the following ways
      • public static ExecutorService newFixedThreadPool(int nThreads)
      • public static ExecutorService newSingleThreadExecutor()
      • The return value of these methods is an ExecutorService object, which represents a thread pool and can execute threads represented by a Runnable object or a Callable object. It provides the following methods
      • Future
        //Create thread pools
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //Put threads in the pool and execute
        pool.submit(new MyRunnable());              
        pool.submit(new MyRunnable());

        //Close thread pool
        pool.shutdown();    

Ways to implement multithreaded programs 3 (Understanding)

  • Submitted is Callable
public class Demo6_Callable {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // Create two threads in the thread pool
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // Put threads in the pool and execute, and use Future to receive results
        Future<Integer> f1 = pool.submit(new MyCallable(100));
        Future<Integer> f2 = pool.submit(new MyCallable(50));

        System.out.println(f1.get());
        System.out.println(f2.get());

        pool.shutdown(); // Close thread pool
    }

}

// Find the sum of 1-num
class MyCallable implements Callable<Integer> {
    private int num;

    public MyCallable(int num) {
        this.num = num;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= num; i++) {
            sum += i;
        }

        return sum;
    }

}
  • The Advantages and Disadvantages of Mode 3 of Multithread Programming Implementation

    • Benefits:

      • Can have a return value
      • Can throw an exception
    • Disadvantages:

      • The code is complex, so it's not usually used.

The former is Thread, the second is Runnable, and the third is Callable: Three ways to create multithreading in Java - blog u012843873 - CSDN.NET

Overview and Use of Simple Factory Model (Understanding)

  • A: Overview of Simple Factory Model
    • Also known as the static factory method pattern, it defines a specific factory class responsible for creating instances of some classes.
  • B: Advantages
    • Clients do not need to be responsible for creating objects, thus clarifying the responsibilities of each class.
  • C: Disadvantages
    • This static factory class is responsible for the creation of all objects. If new objects are added or some objects are created differently, the factory class needs to be constantly modified, which is not conducive to later maintenance.
  • D: Case demonstration
    • Animal Abstract class: public abstract Animal {public Abstract void eat ();}
    • Specific dog class: public class Dog extends Animal {}
    • Specific cats: public class Cat extends Animal {}
    • At first, each specific content in the test class creates its own object, but if the task of creating objects is troublesome, someone needs to do it specially, so you know a special class to create objects.
        public class AnimalFactory {
            private AnimalFactory(){}

            //public static Dog createDog() {return new Dog();}
            //public static Cat createCat() {return new Cat();}

            //Improvement
            public static Animal createAnimal(String animalName) {
                if("dog".equals(animalName)) {return new Dog();}
                else if("cat".equals(animale)) {
                        return new Cat();
                }else {
                    return null;
                }
            }
        }

Overview and Use of Factory Method Patterns (Understanding)

  • A: Overview of Factory Method Model
    • The abstract factory class in the factory method pattern is responsible for defining the interface of creating objects. The creation of concrete objects is realized by the concrete class inheriting the abstract factory.
  • B: Advantages
    • Client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class. If new objects are added, it only needs to add a specific class and a specific factory class. It does not affect the existing code. It is easy to maintain later and enhances the expansibility of the system.
  • C: Disadvantages
    • Additional coding is required, which increases the workload.
  • D: Case demonstration

  • Animal Abstract class: public abstract Animal {public Abstract void eat ();}
    Factory interface: public interface Factory {public abstract Animal createAnimal();}
    Specific dog class: public class Dog extends Animal {}
    Specific cats: public class Cat extends Animal {}
    At first, each specific content in the test class creates its own object, but if the task of creating objects is troublesome, someone needs to do it specially, so you know a special class to create objects. It is found that every time code modification is too cumbersome, the factory method is used to improve, providing a specific factory for each specific implementation.
    Dog Factory: public class DogFactory implements Factory{
    public Animal createAnimal() {...}
    }
    Cat Factory: public class CatFactory implements Factory{
    public Animal createAnimal() {...}
    }

Adapter Design Patterns (Mastery)

  • a. What is an adapter
    • When using listeners, you need to define a class event listener interface.
    • Usually there are many methods in the interface, and not all of them are used in the program, but they have to be rewritten, which is very tedious.
    • The adapter simplifies these operations. When we define the listener, we simply inherit the adapter and rewrite the required method.
  • b. Principle of adapter
    • An adapter is a class that implements the listener interface. All abstract methods are rewritten, but all methods are empty.
    • The adapter class needs to be defined as abstract because it makes no sense to call empty methods when creating such objects.
    • The purpose is to simplify the programmer's operation, define the listener to inherit the adapter, and rewrite only the required method.

Java Window (Understanding)

How to create a window and display it

  • Graphical User Interface (GUI).

  • Frame f = new Frame("my window");
    F. setLayout (new FlowLayout ();// Set up Layout Manager
    f.setSize(500,400);//Set Form Size
    f.setLocation(300,200); //Set the position of the form on the screen
    f.setIconImage(Toolkit.getDefaultToolkit().createImage("qq.png"); //Set the title picture
    f.setVisible(true); // Set Form Visible

Layout Manager

  • FlowLayout
    • Rank from left to right.
    • The default layout manager for Panel.
  • BorderLayout
    • East, South, West, North, Middle
    • Frame default layout manager.
  • GridLayout (Grid Layout Manager)
    • Regular Matrix
  • CardLayout
    • tab
  • GridBagLayout (Grid Packet Layout Manager)
    • Irregular Matrix

Form monitoring

Frame f = new Frame("My Form");
//Event sources are forms that register listeners to event sources
//Event objects are passed to listeners
f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
                     //Quit the virtual machine and close the window
        System.exit(0);
    }
});

GUI knowledge you need to know

  • event processing
    • Event: An operation of the user
    • Event Source: Operated Components
    • Listener: An object of a custom class that implements the listener interface and contains event handling methods. It adds the listener to the event source. When an event occurs, the virtual machine automatically calls the event handling method in the listener.

Network programming

Overview of Network Programming (Understanding)

  • A: Computer Network
    • It refers to a computer system that connects multiple computers with independent functions in different geographical locations and their external equipment through communication lines, realizes resource sharing and information transmission under the management and coordination of network operating system, network management software and network communication protocol.
  • B: Network programming
    • It means that data can be exchanged between programs running on different computers to realize network interconnection.

IP Overview of Three Elements of Network Programming

  • Unique identity of each device in the network
  • Each network terminal has a separate address in the network, which we use to transmit data in the network.
  • ipconfig: View native IP192.168.12.42
  • ping: Test connection 192.168.40.62
  • Local loop address: 127.0.0.1 255.255.255.255 is broadcast address
  • IPv4: 4 bytes, 4 0-255. About 4.2 billion, 3 billion in North America and 400 million in Asia. It was exhausted in early 2011.
  • IPv6:8 groups with 4 hexadecimal digits in each group.
  • 1a2b:0000:aaaa:0000:0000:0000:aabb:1f2f
  • 1a2b::aaaa:0000:0000:0000:aabb:1f2f
  • 1a2b:0000:aaaa::aabb:1f2f
  • 1a2b:0000:aaaa::0000:aabb:1f2f
  • 1a2b:0000:aaaa:0000::aabb:1f2f

Overview of Port Number of Three Elements of Network Programming

  • Unique identification of each program on the device
  • Every network program needs to bind a port number. When transferring data, in addition to determining which machine to send, it also needs to specify which program to send.
  • Port number range from 0-65535
  • Writing network applications requires binding a port number, try to use 1024 or more, 1024 or less are basically occupied by system programs.
  • Common ports
    • mysql: 3306
    • oracle: 1521
    • web: 80
    • tomcat: 8080
    • QQ: 4000
    • feiQ: 2425

Protocol of Three Elements of Network Programming (Mastery)

  • A set of rules, standards, or conventions established for data exchange in computer networks.
  • UDP
    • For connectionless, data is insecure and fast. There is no distinction between client and server. (Similar to texting, no matter whether the number exists or not, or whether the other party can receive it, you send the number anyway.)
  • TCP
    • Connection-oriented (three handshakes), data security, slightly lower speed. It is divided into client and server.
    • Three handshakes: the client first initiates a request to the server, the server responds to the request and transmits data (similar to calling the goddess, you have to wait for the goddess to answer before you can express).
    • HTTP protocol is based on TCP protocol

Knowledge of Java network programming: Java Network Programming - Ruthless - Blog Garden

Diagram of Socket Communication Principle (Understanding)

  • A: Overview of Socket Sockets:
    • Only when IP addresses and port numbers with unique identifiers are combined on the network can a unique identifier socket be formed.
    • Socket s are available at both ends of the communication.
    • Network communication is actually the communication between Socket s.
    • Data is transmitted between two Socket s through IO streams.
    • Socket is created in the application program. It establishes a relationship with the driver through a binding mechanism and tells itself the corresponding IP and port.

UDP Transport (Understanding)

  • 1. Send
    • Create Datagram Socket with random port number
    • Create Datagram Packet, specify data, length, address, port
    • Sending Datagram Packet with Datagram Socket
    • Close Datagram Socket
  • 2. Receive Receive
    • Create DatagramSocket, specify port number
    • Create Datagram Packet, specify the array, length
    • Receiving Datagram Packet with Datagram Socket
    • Close Datagram Socket
    • Getting data from Datagram Packet
  • 3. Receiver obtains ip and port number

    • String ip = packet.getAddress().getHostAddress();
    • int port = packet.getPort();
  • 4. List demonstration:
    1.Send

        // Items to be sent
        String str = "what are you what are you?";
        //Creating a Socket is equivalent to creating a wharf (equivalent to sending a courier to a courier company without filling in the sender's information).
        DatagramSocket socket = new DatagramSocket();
        //Creating a Packet is equivalent to a container.
        //Items are loaded into express delivery (express delivery needs to be selected according to the size of the items). Express delivery needs to be sent to room 6666 in 127.0.0.1 district.
        DatagramPacket packet =                                     
                new DatagramPacket(str.getBytes(), str.getBytes().length, 
                        InetAddress.getByName("127.0.0.1"), 6666);
        //Delivery, send out data (express company send express)
        socket.send(packet);    
        //Close the wharf, express delivery company sent out, can collect money, close the deal
        socket.close(); //The bottom layer is the io stream, which needs to be turned off to release resources.   

2.Receive

        //Creating a Socket is equivalent to creating a wharf, but you have to use a port number. Without this port address, the goods can't find their destination.
        //As the recipient of express delivery, there must be a door number.
        DatagramSocket socket = new DatagramSocket(6666);
        //Creating a Packet is equivalent to creating a container (receiving express delivery, carrying things for express delivery)
        //The first 1024 is equivalent to a box with a capacity of 1024, and the second 1024 is the largest number of goods that can be packed. The number of front and rear boxes should be the same.
        DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
        //Receiving and receiving data
        socket.receive(packet);                                 

        //Getting Data (Dismantling Express)
        byte[] arr = packet.getData();                          
        //Get the number of valid bytes
        int len = packet.getLength();                           
        System.out.println(new String(arr,0,len));
        socket.close();//The bottom layer is the io stream, which needs to be turned off to release resources.
UDP Transmission Optimization
  • 1. Send of sender
        // Create keyboard entry objects
        Scanner sc = new Scanner(System.in);
        // Creating a Socket is equivalent to creating a wharf.
        DatagramSocket socket = new DatagramSocket();

        // Gets the string entered by the keyboard
        while (true) {
            String line = sc.nextLine();
            if ("quit".equals(line)) {
                break;
            }
            // Creating a Packet is equivalent to a container
            DatagramPacket packet = new DatagramPacket(line.getBytes(), 
                    line.getBytes().length,InetAddress.getByName("127.0.0.1"), 
                    6666);
            // Delivery, sending out data
            socket.send(packet);
        }
        // Shut down the wharf
        socket.close();
  • 2. Receive at Receive
        //Creating a Socket is equivalent to creating a wharf.
        DatagramSocket socket = new DatagramSocket(6666);   
        //Creating a Packet is equivalent to creating a container.
        DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

        //Receiving and receiving data
        while(true) {
            socket.receive(packet);                                 
            //get data
            byte[] arr = packet.getData();
            //Get the number of valid bytes
            int len = packet.getLength();
            //Get the ip address
            String ip = packet.getAddress().getHostAddress();
            //Get the port number
            int port = packet.getPort();                            
            System.out.println(ip + ":" + port + ":" + new String(arr,0,len));
        }

TCP Protocol (Mastery)

  • 1. Client
    • Create Socket Connection Server (specify ip address, port number) to find the corresponding server through ip address
    • Call the getInputStream() and getOutputStream() methods of Socket to obtain IO flows connected to the server
    • The input stream can read the data written by the output stream of the server.
    • The output stream can write the input stream from the data to the server.
  • 2. Server
    • Create ServerSocket (need to specify port number)
    • Call the accept() method of ServerSocket to receive a client request and get a Socket
    • Call Socket's getInputStream() and getOutputStream() methods to get IO flows connected to the client
    • Input stream can read data written by client output stream
    • The output stream can write the input stream of data to the client.

TCP Protocol Code Optimization
  • 1. Client
        Socket socket = new Socket("127.0.0.1", 9999);      //Create Socket to specify ip address and port number
        InputStream is = socket.getInputStream();           //Get the input stream
        OutputStream os = socket.getOutputStream();         //Get the output stream
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        PrintStream ps = new PrintStream(os);

        System.out.println(br.readLine());
        ps.println("I want to enroll in an employment class.");
        System.out.println(br.readLine());
        ps.println("Ye did not study any more.");
        socket.close();
  • 2. Server
        ServerSocket server = new ServerSocket(9999);   //Create a server
        Socket socket = server.accept();                //Accept client requests
        InputStream is = socket.getInputStream();       //Get the input stream
        OutputStream os = socket.getOutputStream();     //Get the output stream

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        PrintStream ps = new PrintStream(os);

        ps.println("Welcome to the consultation Podcast");
        System.out.println(br.readLine());
        ps.println("Full Report,Please report the next issue.");
        System.out.println(br.readLine());
        server.close();
        socket.close();
Server is multi-threaded (master)
    ServerSocket server = new ServerSocket(9999);   //Create a server
        while(true) {
            final Socket socket = server.accept();              //Accept client requests
            new Thread() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        PrintStream ps = new PrintStream(socket.getOutputStream());
                        ps.println("Welcome to the consultation Podcast");
                        System.out.println(br.readLine());
                        ps.println("Full Report,Please report the next issue.");
                        System.out.println(br.readLine());
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

reflex

Class loading overview and timing)

  • A: Overview of Class Loading
    • When a program wants to use a class, if the class has not been loaded into memory, the system will initialize the class by loading, connecting and initializing three steps.
    • Load
      • That is to read the class file into memory and create a Class object for it. The system creates a Class object when any class is used.
    • Connect
      • Verify that there is a correct internal structure and that it is consistent with other classes
      • Prepare to allocate memory for static members of the class and set default initialization values
      • Parsing replaces symbolic references in class binary data with direct references
    • Initialization is the initialization step we talked about before.
  • B: Loading time
    • Create instances of classes
    • Access static variables of classes, or assign values to static variables
    • Calling static methods of classes
    • Mandatory creation of java.lang.Class objects corresponding to a class or interface using reflection
    • Initialize subclasses of a class
    • Running a main class directly using the java.exe command

Overview and Classification of Class Loaders

  • A: An overview of class loaders
    • It is responsible for loading. class files into memory and generating corresponding Class objects for them. Although we do not need to care about the class loading mechanism, we can better understand the operation of the program by understanding this mechanism.
  • B: Classification of Class Loaders
    • Bootstrap ClassLoader Root Class Loader
    • Extension ClassLoader Extension Class Loader
    • Sysetm ClassLoader System Class Loader
  • C: The role of class loaders
    • Bootstrap ClassLoader Root Class Loader
      • Also known as boot class loader, responsible for loading Java core classes
      • For example, System,String, etc. In the rt.jar file of JRE in the lib directory of JDK
    • Extension ClassLoader Extension Class Loader
      • Responsible for loading jar packages in JRE's extended directory.
      • ext directory in the lib directory of JRE in JDK
    • Sysetm ClassLoader System Class Loader
      • Responsible for loading class files from java commands at JVM startup, as well as jar packages and class paths specified by classpath environment variables

An overview of Java class loading and class loaders: Deep Understanding of Java: Class Loading Mechanism and Reflection-Milk, Sugar-Free-Blog Garden

Overview of Reflection

  • A: Overview of Reflection

    • JAVA reflection mechanism is that in the running state, all attributes and methods of any class can be known.
    • For any object, it can call any of its methods and attributes.
    • This dynamic acquisition of information and the function of dynamically invoking methods of objects is called the reflection mechanism of java language.
    • To dissect a class, you must first obtain the bytecode file object of that class.
    • Anatomy uses methods in Class classes, so first we need to get the object of Class type corresponding to each bytecode file.
  • B: Three ways

    • A: The getClass() method of the Object class to determine whether two objects are the same bytecode file
    • b: Static attribute class, lock object
    • C: The static method forName() in the Class class reads the configuration file
  • C: Case demonstration
    • Three Ways to Get class File Objects
        Class clazz1 = Class.forName("com.heima.bean.Person");//Package name. Class name
        Class clazz2 = Person.class;

        Person p = new Person();
        Class clazz3 = p.getClass();

        System.out.println(clazz1 == clazz2);//true
        System.out.println(clazz2 == clazz3);//true

The Java reflection mechanism is described in detail: Java Reflection Mechanisms Detailed - Java Junior Coder - Blog Garden

Examples of Class.forName() reading configuration files

  • Juicer juicing case
  • Fruit apple banana orange squeeze

1. Main code:

        public class Demo2_Reflect {

            /**
             * Juicer juicing case
             * Fruit apple banana orange squeeze
             * @throws Exception 
             */
            public static void main(String[] args) throws Exception {
                /*Juicer j = new Juicer();
                //j.run(new Apple());
                j.run(new Orange());*/
                BufferedReader br = new BufferedReader(new FileReader("config.properties"));    //Create input stream objects and associate configuration files
                Class<?> clazz = Class.forName(br.readLine());                                  //Read a line of configuration file to get bytecode objects of this class
                Fruit f = (Fruit) clazz.newInstance();                                          //Creating instance objects through bytecode objects
                Juicer j = new Juicer();
                j.run(f);
            }

        }
        interface Fruit {
            public void squeeze();
        }

        class Apple implements Fruit {
            public void squeeze() {
                System.out.println("Squeeze out a glass of apple juice");
            }
        }

        class Orange implements Fruit {
            public void squeeze() {
                System.out.println("Squeeze out a glass of orange juice");
            }
        }

        class Juicer {
            public void run(Fruit f) {
                f.squeeze();
            }

        }

2. Configuration file config.properties

com.heima.reflect.Apple

Obtaining the construction method of band parameters by reflection and using it

  • Constructor
    • Class class's newInstance() method is to create objects using the class's nonparametric constructor. If a class has no nonparametric constructor, it can't be created like this. You can call the getConstructor(String.class,int.class) method of the Class class to get a specified constructor and then call the newInstance("Zhang") of the Constructor class. Method Creation Objects
        //At this point Person has a Person(String name,int age) parametric constructor
        Class clazz = Class.forName("com.heima.bean.Person");
        //Person p = (Person) clazz.newInstance();  //Creating Objects by Nonparametric Construction
        //System.out.println(p);

        //Obtaining parametric structures
        Constructor c = clazz.getConstructor(String.class,int.class);
        //Create objects by parametric construction
        Person p = (Person) c.newInstance("Zhang San",23);                     
        System.out.println(p);

Person object main code:

package com.heima.bean;

public class Person {
    private String name;
    private int age;
    public Person() {
        super();

    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        //Determine whether the bytecode file of the calling object and the incoming object is the same bytecode file
        if (this.getClass() != obj.getClass())      
            return false;
        Person other = (Person) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

    public void eat() {
        System.out.println("I had a Money Leopard today.");
    }

    public void eat(int num) {
        System.out.println("I ate it today." + num + "Monkey Leopard");
    }

    public void eat(int num,String status) {
        System.out.println("I ate it today." + num + "Monkey Leopard"+"  ,"+"Eating"+status);
    }
}

Obtain member variables by reflection and use them

  • Field
    • Class.getField(String) method can obtain the specified field in the class (visible), if it is private, it can be obtained by getDeclaedField("name") method, and it can set the value of the field on the specified object by set(obj, "Lisi") method. If it is private, it can call setAccessible(true) to set access rights first, and then use get. The specified field calls get(obj) to get the value of the field in the specified object
        //At this point Person has a Person(String name,int age) parametric constructor
        Class clazz = Class.forName("com.heima.bean.Person");
        //Obtaining parametric structures
        Constructor c = clazz.getConstructor(String.class,int.class);
        //Create objects by parametric construction
        Person p = (Person) c.newInstance("Zhang San",23);                     

        //Field f = clazz.getField("name"); //Get the name field
        //f.set(p, "Li Si");//You can't change the value of a name because the name attribute is private and requires a violent reflex.

        //Violent Reflex Get Fields (like you want to rob a person's car)
        Field f = clazz.getDeclaredField("name");
        //Get rid of private rights (here's like grabbing the key to that car, and then you can do whatever you want)
        f.setAccessible(true);
        //Modify the name field of p
        f.set(p, "Li Si");

        System.out.println(p);

Obtain the method by reflection and use it

  • Method
    • Class.getMethod(String, Class... ) And lass. getDeclared Method (String, Class... ) Method can get the specified method in the class and call invoke(Object, Object... ) This method can be called, Class.getMethod("eat") invoke(obj) Class.getMethod("eat", int.class) invoke(obj,10)
        Class clazz = Class.forName("com.heima.bean.Person");
        //Obtaining parametric structures
        Constructor c = clazz.getConstructor(String.class,int.class);
        //Create objects by parametric construction
        Person p = (Person) c.newInstance("Zhang San",23);                     

        //Getting eat method
        Method m = clazz.getMethod("eat");                              
        m.invoke(p);//// I had a Money Leopard today.

        //eat method for obtaining a parameter
        Method m2 = clazz.getMethod("eat", int.class);                  
        m2.invoke(p, 10);//Today I ate 10 meals of Monkey Leopard

        //eat method for obtaining two parameters
        Method m3 = clazz.getMethod("eat", int.class,String.class);                 
        m3.invoke(p, 10,"Not full");//Today, I ate 10 meals of Money Leopard, but I was not full.

Generic exercises

  • A: Case demo: Override generic checking by reflection
    • How to implement an object of ArrayList that adds a string data to the collection?
    /**
     * @param args
     * ArrayList<Integer>How to implement an object that adds a string data to the set?
     * Generics are valid only at compile time and are erased at run time
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(111);
        list.add(222);

        //Getting bytecode objects
        Class clazz = Class.forName("java.util.ArrayList"); 
        //Get the add method
        Method m = clazz.getMethod("add", Object.class);                
        m.invoke(list, "abc");

        System.out.println(list);

    }
  • B: Case demonstration: Write a generic reflection to set an object's property to a specified value
    • public void setProperty(Object obj, String propertyName, Object value) {} This method sets the value of an attribute named propertyName in an obj object to value.

1.Tool tool class:

package com.heima.test;

import java.lang.reflect.Field;

public class Tool {
    //This method sets the value of an attribute named propertyName in the obj object to value.
    public void setProperty(Object obj, String propertyName, Object value) throws Exception {
        Class clazz = obj.getClass();                   //Getting bytecode objects
        Field f = clazz.getDeclaredField(propertyName); //Violent reflex acquisition field
        f.setAccessible(true);                          //Delete permissions
        f.set(obj, value);
    }
}

2. Test class

        Student s = new Student("Zhang San", 23);
        System.out.println(s);

        Tool t = new Tool();
        t.setProperty(s, "name", "Li Si");
        System.out.println(s);
  • C: Case Demonstration: Do Questions as Required
    • A class is known and defined as follows:
      • package cn.itcast.heima;
      • public class DemoClass {
        public void run() {
        System.out.println("welcome to heima!");
        }
        }
      • (1) Write a configuration file in Properties format with the full name of the configuration class.
      • (2) Write a program, read the Properties configuration file, get the full name of the class, load the class, and run the run method in a reflective way.

1.DemoClass main code:

package com.heima.test;

public class DemoClass {
    public void run() {
        System.out.println("welcome to heima!");
    }
}

2.xxx.properties

com.heima.test.DemoClass

3. Test code

        //Create an input stream Association xxx.properties
        BufferedReader br = new BufferedReader(new FileReader("xxx.properties"));
        //Read the class name in the configuration file to get the bytecode object
        Class clazz = Class.forName(br.readLine());

        //Creating objects through bytecode objects
        DemoClass dc = (DemoClass) clazz.newInstance();
        dc.run();

Overview and Implementation of Dynamic Agent

  • A: Overview of Dynamic Agents

    • Agent: What should have been done by oneself should have been done by someone else. The person invited is the agent.
    • Examples: Buying tickets at home for the Spring Festival
    • Dynamic Agent: This object is generated in the process of running the program, and the object generated in the process of running the program is actually what we have just reflected on, so the dynamic agent actually generates an agent through reflection.

    • A Proxy class and an InvocationHandler interface are provided under the java.lang.reflect package in Java, which can be used to generate dynamic proxy objects. The proxy provided by JDK can only be proxy for interfaces. We have more powerful proxy cglib, methods in the Proxy class to create dynamic proxy class objects

    • public static Object newProxyInstance(ClassLoader loader,Class
public interface User {
    void add();
    void delete();

}

2.UserImp inherits the User interface:
I think permission validation is needed before using add() method and delete method each time, and then it can be written to the log file. If each method needs to do it by itself, it will be bloated. Here we suggest using dynamic proxy mode to do it.

public class UserImp implements User {

    @Override
    public void add() {
        //System.out.println("permission check");
        System.out.println("Adding functionality");
        //System.out.println("log record");
    }

    @Override
    public void delete() {
        //System.out.println("permission check");
        System.out.println("Delete function");
        //System.out.println("log record");
    }

}

3.MyInvocationHandler

public class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("Privilege Check");
        method.invoke(target, args);                    //Method to execute the proxy target object
        System.out.println("Logging");
        return null;
    }

}

4. Test code:

        UserImp ui = new UserImp();
        ui.add();
        ui.delete();

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

         /*public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,
         InvocationHandler h)
         */
        MyInvocationHandler m = new MyInvocationHandler(ui);
        User u = (User)Proxy.newProxyInstance(ui.getClass().getClassLoader(),
                ui.getClass().getInterfaces(), m);
        u.add();
        u.delete();

Overview and Use of Template Design Patterns

  • A: Overview of template design patterns
    • The template method pattern defines the skeleton of an algorithm and delays the implementation of a specific algorithm to a subclass.
  • B: Advantages and disadvantages
    • a:Advantages
      • Using template method pattern, while defining the algorithm skeleton, it can flexibly implement specific algorithms to meet the flexible and changeable needs of users.
    • b: Disadvantages
      • If the algorithm skeleton is modified, the abstract class needs to be modified.
public class Demo1_Template {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //What we do here is not in line with our Java object-oriented thinking.
        /*long start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++) {
            System.out.println("x");
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);*/
        Demo d = new Demo();
        System.out.println(d.getTime());
    }

}

abstract class GetTime {
    //To prevent subclasses from overwriting this method
    public final long getTime() {
        long start = System.currentTimeMillis();
        code();
        long end = System.currentTimeMillis();
        return end - start;
    }

    //If you write code here, it's not good.
    public abstract void code();
}

class Demo extends GetTime {

    @Override
    public void code() {
        int i = 0;
        while(i < 1000) {
            System.out.println("x");
            i++;
        }
    }
}

The Java design patterns that have been learned so far:
1. Decoration
2. Single case
3. Simple factories
4. Factory Method
5. Adapter
6. Template

Detailed Description of 23 Design Patterns in Java Development - maowang - Blog Garden

New features of JDK 1.5:

1. Automatically disassemble and pack boxes
2. Generics
3. Variable parameters
4. Static import
5. Enhance for cycle
6. Mutex Lock
7. Enumeration

Enumeration classes for new features of JDK5

  • A: Overview of Enumeration
    • It refers to listing the values of variables one by one. The values of variables are limited to the range of the values listed. Examples: 7 days a week, 12 months a year, etc.
  • B: Recall the singleton design pattern: a singleton class is a class with only one instance
    • So many example classes are instances of a class, but not infinite number of instances, but finite number of instances. This is the enumeration class.
  • C: Case demonstration
    • Implementing enumeration classes by oneself
public class Week {
    //In fact, enumeration is an extension of the singleton design pattern.
    public static final Week MON = new Week();
    public static final Week TUE = new Week();
    public static final Week WED = new Week();

    private Week(){}                        //Private constructs do not allow other classes to create objects of this class
}
Notes for enumeration
  • A: Case demonstration
    • To define an enumeration class, use the keyword enum
    • All enumerated classes are subclasses of Enum
    • The first line of the enumeration class must be an enumeration item, and the semicolon after the last enumeration item can be omitted, but if the enumeration class has something else, the semicolon cannot be omitted. Recommend not to omit
    • Enumeration classes can have constructors, but must be private, which by default is private.
    • Enumeration classes can also have abstract methods, but enumeration items must override this method
Common methods for enumerating classes
  • A: Common methods for enumerating classes
    • int ordinal()// enumerations are numbered, starting with 0
    • int compareTo(E o)// Compare numbers
    • String name()// Gets the instance name
    • String to String ()// If not overridden, get the instance name
    • T valueOf(Class type,String name) // / Get enumeration items through bytecode objects
    • values()// This method is not found in the JDK document, but each enumeration class has this method, which is very convenient to traverse all the enumerated values of the enumeration class.

New features of JDK7

  • A: Binary literals
  • B: Digital literals can be underlined
  • C:switch statements can use strings
  • D: Simplification of generics, diamond generics
  • E: Merge multiple catch es of exceptions, each using or|
  • F:try-with-resources statement

New features of JDK8

  • A method body can be defined in the interface. If it is not static, it must be modified with default (object call)
  • If it's static, it's not necessary (class name calls, object calls are not allowed)
        class Test {
            public void run() {
                final int x = 10;
                class Inner {
                    public void method() {
                        System.out.println(x);
                    }
                }

                Inner i = new Inner();
                i.method();
            }

        }

Question: Local internal classes must be final ized when accessing local variables in their methods. Why?
Because when this method is called, if the local variable is not modified with final, its life cycle is the same as that of the method. When the method stack, the local variable will disappear. If the local internal class object has not disappeared immediately and wants to use this local variable, it will disappear. If the final modification is used, it will be loaded in the class. When entering the constant pool, the constant of the constant pool can continue to be used even though the method stack is still there.

1. New features of JDK 1.5: New features of JDK 1.5 - Tianmu Personal Blog - Blog Channel - CSDN.NET
2. New features of JDK 1.6: New features of JDK 1.6 - Tianmu Personal Blog - Blog Channel - CSDN.NET
3. New features of JDK 1.7: New features of JDK 1.7 - Tianmu Personal Blog - Blog Channel - CSDN.NET
4. New features of JDK 1.8: New features of JDK 1.8 - Tianmu Personal Blog - Blog Channel - CSDN.NET

Chapter Four Review Links:
Java Basic Review (IV) - it Rookie's Flying Dream - Blog Channel - CSDN.NET

There's no next article, JavaSE Foundation Review to finish here

Posted by daydreamer on Thu, 11 Jul 2019 13:00:02 -0700