Java boost 2

1. Detailed explanation of Java collection classes

  1. Connection interface
    1. The collection can be understood as a dynamic array of objects, the difference is that the content of the objects in the collection can be expanded arbitrarily
    2. Collection features:
      high performance
      easy to extend and modify
    3. Common subclasses of Collection
      List
      Set
      Queue
  2. List interface
    1. The List interface can store arbitrary data, and the content in the List interface can be repeated
    2. Common subclasses of List interface:
      ArrayList
      Vector
    3. Common operations:
      Determine whether the collection is empty: boolean isEmpty()
      Find whether the specified object exists: int indexOf(Object o)
Compare ArrayList Vector
launch time Released after JDK1.2 JDK1.0 launched
performance Asynchronous processing, high performance Synchronous processing, low performance
thread safety are not thread safe are thread safe
  1. Set interface
    1. Duplicate elements cannot be added to the Set interface, but they can be sorted
    2. Common subclasses of Set interface
      Hash storage: HashSet
      ordered storage: TreeSet
  2. Iterator interface
    1. Standard operations on collection output:
      standard practice, using the Iterator interface
    2. Operation principle:
      Iterator is a special iterative output interface. Iterative output is to judge the elements one by one to determine whether they have content, and if there is content, take out the content.
  3. Map interface
    1. Save form:
      Key—>value way to save
    2. Common subclasses:
      HashMap: unordered storage, key does not allow duplication (non-thread-safe)
      Hashtable: unordered storage, key does not allow duplication (thread-safe)

2. IO operations in Java

  1. Function:
    IO is also written as "I/O", which can be understood as In and Out, that is, input and output. Therefore, the basic functions of the IO system are: reading and writing.

  2. IO style

    • Function: read and write data on the device, hard disk files, memory, keyboard, network...
    • According to the direction of data, it can be divided into: input stream, output stream
    • According to the type of data processed, it can be divided into: byte stream, character stream
  3. byte stream and character stream

    • Byte streams can handle all types of data, such as MP3, pictures, text, video, etc. When reading, a byte is returned when a byte is read.
    • The corresponding classes in java all end with "Stream".

    • Character streams can only handle plain text data, such as txt text. When reading, read one or more bytes, first look up the specified encoding table, and then return the found characters.

    • The corresponding classes in Java all end with "Reader" or "Writer"

  4. Characters, bytes and encodings

Byte

  • Byte is a unit for transmitting information through a network or storing information in a hard disk or memory. It is a unit of measurement used by computer information technology to measure storage capacity and transmission capacity.
  • 1 byte is equal to 8 bits of binary, that is, an 8-bit binary number, which is a very specific storage space.
    Such as 0x01, 0x45, 0xFA,…

character (Char)

  • A character is a number that people use, a symbol in an abstract sense.
    Such as'1','中','a','¥','$',…

Character set (Charset)

"Character set" is also called "encoding".

The difference between the three, please see the following table:
javaByteCharDif
5. Use byte stream to read and write data

  • Use fileInputStream and fileOutputStream to copy files
public static void main(String[] args) {
    try {
        FileInputStream fileInputStream = new FileInputStream("Java01/text.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("Java01/newText.txt");

        byte input[] = new byte[50];

        while (fileInputStream.read(input) != -1) {
            fileOutputStream.write(input);
        }

        fileInputStream.close();
        fileOutputStream.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


6. Read and write data using a buffered byte stream

public static void main(String[] args){
    try {
        FileInputStream fileInputStream = new FileInputStream("Java01/text.txt");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream,1000000);//设置缓冲区的大小

        //大型文件对应的数组可以大一些,小文件对应的数组小一些
        byte input[]  = new byte[100000];
        int count = 0;
        long before = System.currentTimeMillis();               //读取之前的时间
        while (bufferedInputStream.read(input)!=-1){
            count++;
        }
        bufferedInputStream.close();
        fileInputStream.close();
        System.out.println(System.currentTimeMillis()-before+"ms"); //读取之后和之前的差值
        System.out.println("都去了"+ count +"次");


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Description: Find the data with the most efficient file reading by debugging the size of the buffer and byte array multiple times.
7. Use the character stream to read and write data The
same is true, copy the file, and now use the character stream to read and write data, the example is as follows:

public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("Java01/text.txt");
            FileOutputStream fileOutputStream = new FileOutputStream("Java01/newText.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");//InputStreamReader使用指定的 charset 读取字节并将其解码为字符。
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");

            char input[] = new char[100];
            int l = 0;
            while ((l = inputStreamReader.read(input)) != -1) {
                outputStreamWriter.write(input, 0, l);          //将字符读入数组中的某一部分。
            }
//            while (inputStreamReader.read(input) != -1) {     //读入数组的的字符会存在偏移,即多读出字符
//                outputStreamWriter.write(input);
//            }

            outputStreamWriter.close();
            inputStreamReader.close();
            fileOutputStream.close();
            fileInputStream.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


8. Read and write data using a buffered character stream

That is, adding BufferedReader and BufferedWriter, there will be a problem, that is, the newline character will be discarded when writing the file, which can be
instantiated using PrintWriter PrintWriter:

PrintWriter pw = new PrintWriter(outputStreamWriter,true);//实例化并强制自动刷新缓冲区数据


9. FileReader与FileWriter

  • Use FileReader and FileWriter to read and write some plain text files, and read and write character-based files. The usage is similar to the above-mentioned file reading methods, so I won't go into details.


10. RandomAccessFile random file read and write

Example code:
MultiwriterFile.java

package com.william.RandomAccessFileTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Created by william on 2016/11/25.
 */
public class MultiwriterFile {
    static File file = new File("Java01/text.txt");

    public static void main(String[] args) {
//        if (file.exists()) {
//            file.delete();
//        }
//        new WriteFile(file,1).start();
//        new WriteFile(file,2).start();
//        new WriteFile(file,3).start();
//        new WriteFile(file,4).start();
//        new WriteFile(file,5).start();

        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            randomAccessFile.seek(300);
            byte input[] = new byte[20];
            randomAccessFile.read(input);
            String str = new String(input);
            System.out.print(str);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

WriteFile.java

package com.william.RandomAccessFileTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Created by william on 2016/11/25.
 */
public class WriteFile extends Thread {
    File file;
    int block;
    int L = 100;

    public WriteFile(File file, int block) {
        this.file = file;
        this.block = block;
    }

    /**
     * 文件随机读取示意图:
     * 1                 2(100)            3                 4(300)            5
     * |-----------------|-----------------|-----------------|-----------------|--------
     * 0xL<-----100----->1xL
     */
    public void run() {
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek((block - 1) * L);
            randomAccessFile.writeBytes("This is block" + block);
            for (int i=0;i<20;i++) {
                randomAccessFile.writeBytes("-");
            }
            randomAccessFile.writeBytes("\n");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Execute the write operation and output the result:

This is block1——————–
This is block2——————–
This is block3——————–
This is block4——————–
This is block5——————–

Execute read operation output result:
output: output 20 bytes length

This is block4——


11. Use the Apache IO library to manipulate IO and files

The operation of the original java file is encapsulated, which is more convenient to use. For details, please refer to the official API document of Apache.


3. Java multi-threaded programming

  1. threads and processes

Thread:

  • Individual sequential control flow in a program
  • The new city itself relies on programs to run
  • A thread is the sequential flow of control in a program and can only use the resources and environment allocated to the program

process:

  • program in execution
  • A process can contain one or more threads
  • A process must contain at least one thread

Single thread:

  • There is only one thread in the program, in fact the main method is a main thread

Multithreading:

  • Multithreading is running multiple tasks in one program
  • The purpose of multithreading is to make better use of cpu resources


2. Thread implementation

  • In java, there are two types of thread implementations:
    ①. Inheriting the Thread class
    ②. Implementing the Runnable interface
  • Thread class:
    The Thread class is defined in the java.lang package. To inherit the Thread class, the run() method must be rewritten.
    Definition format:
class className extends Thread{
    run(){};
}

Example:

public class MyThread extends Thread {
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(name + ":" + i);
        }
        super.run();
    }
}

Description: When using Start to start the thread in the main method, we can see that the two threads are executed in parallel, that is, whoever gets the CPU resources first will execute it, not sequentially.

Look at some of the output results:


B:25
B:26
B:27
B:28
B:29
A:0
B:30
A:1
A:2
A:3

  • Runnable interface

Implement the run method in the Runnable interface, which is the same as the run method of Thread. When called in the main method, it is called as follows:

MyRunnable r = new MyRunnable("A");
Thread t = new Thread(r);
t.start();


3. The state of the thread

Threads also have fixed operating states:

  • Create state: a multithreaded object is ready
  • Ready state: The start() method is called, waiting for the cpu to schedule
  • Running state: execute the run() method
  • Blocking state: temporarily stop execution, possibly handing over resources to other threads for use
  • Terminated state (dead state): thread destroyed


4. Common methods of threads

  • Get the thread name
    getName()
  • Get the current thread object
    currentThread()
  • Determine whether the thread starts
    isAlive()
  • Forced operation of the thread
    join()
  • Thread's sleep
    sleep()
  • polite
    yield()


5. Thread priority

Priority order settings:

  • 1-MIN_PRIORITY
  • 10-MAX_PRIORITY
  • 5-NORM_PRIORITY
    if nothing is set the default value is 5


6. Synchronization and Deadlock

  • Synchronized code
    block Add the "synchronized" keyword to a code block, then this code block is called a synchronized code block
  • Synchronized code block format:
    synachronized (synchronized object) {
    code block that needs to be synchronized;
    }
  • Synchronized Methods
    In addition to code blocks that can be synchronized, methods can also be synchronized
  • Method synchronization format:
    synchronized void method name(){}
    synchronization instance:
class MyThreadDemo implements Runnable {

    private int ticket = 5;

    public void run() {
        for (int i = 0; i < 10; i++) {
            tell();
        }
    }

    public synchronized void tell() {
        if (ticket > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("车票:" + ticket--);
        }
    }
}

public class synchronizedtest {
    public static void main(String[] args) {
        MyThreadDemo m = new MyThreadDemo();
        Thread t1 = new Thread(m);
        Thread t2 = new Thread(m);
        Thread t3 = new Thread(m);
        t1.start();
        t2.start();
        t3.start();
    }
}

The deadlock is equivalent to playing tricks with two people, for example: Zhang San has ten dollars, Li Si has a book, Zhang San said, you give me the book first, I will give you the money, Li Si said you first Give me money, and I will give you the book. If two people don't want to let each other go, they will fall into waiting, and there will be a deadlock situation.


7. The life cycle of the thread is
not explained, the above picture:
threadLife


4. HTTP communication in Java

  1. Use Http's Get method to read network data

Look at the following blog, the video is quite loose, but I would like to thank the teachers of the video and the bloggers of the blog. :)
http://blog.csdn.net/luckyzhoustar/article/details/50259209
2. Use Http Post to communicate with the network

Nothing to say, or a blog post:
http://blog.csdn.net/thl331860203/article/details/51783434
3. Use HttpClient for Get communication

Use the jar package of Apache's HttpClient, the specific operation, check it online yourself, it is not like writing.
4. Use HttpClient for Post communication

Use the jar package of Apache's HttpClient, the specific operation, check it online yourself, it is not like writing.
For reference:
https://www.oschina.net/code/snippet_1591393_46723


Five. Inner class in Java, anonymous inner class understanding

http://blog.csdn.net/zzjjiandan/article/details/9189943

Generally speaking, there are four kinds of inner classes: regular inner classes, static inner classes, partial inner classes, and anonymous inner classes.

  • Regular inner classes The biggest difference between
    regular inner classes and ordinary classes is that they can access (here, access means read and write) the private instance fields of the outer class.
    Specific reference blog:
    http://blog.csdn.net/l294265421/article/details/46574009

  • Static inner class The comparison of
    static inner class and ordinary class is very good, thanks to the blogger:
    http://kenby.iteye.com/blog/1603803

  • local inner class

    1. The modifiers public and private, protected cannot be used before a local inner class.
    2. A variable with the same name as the outer class can be defined
      If inner class does not have a variable with the same name as the outer class, the instance variable of the outer class can be directly accessed in the inner class

      If there is a variable in the inner class with the same name as the outer class, the variable of the inner class is accessed directly with the variable name, and the variable of the inner class is also accessed with this.variable name.

      The outer class variable is accessed with the outer class name .this. inner class variable name

    3. Static variables and methods cannot be defined
    4. You can access local variables of the outer class (i.e. variables inside methods), but the variables must be final
    5. Can access all members of the outer class

Example:
http://blog.csdn.net/l294265421/article/details/46583475

Vignette: About the order of instantiation of classes

1. When instantiating an object of a class, first instantiate the member variables of the class, and then execute the constructor of the class.
2. When instantiating a member variable of a class, first instantiate the static member variable, and then instantiate the non-static member variable.
3. The static member variable of a class is instantiated only once, that is, there is only one copy, which is shared among all objects of the class.
4. When the static member function of a class is executed, the object of the class is not generated. Therefore, only the static member variables of the class will be instantiated, and the non-static member variables will not be instantiated, and the constructor will not be executed.

It is best to write a small example by yourself, and then debugger it yourself, so that it is easier to understand the above summary, you can use the following small example:

class A{
    private int a = 10;
    private static int AA = 100;

    public A(int a) {
        this.a = a;
    }

    public void printA(){
        System.out.println("this is A");
    }

    public static void printText(){
        System.out.println("come here!");
    }

}

public class newclasstest {

    public static void main(String[] args){
        A.printText();
        A a = new A(22);
        a.printA();
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325945089&siteId=291194637