Object-Oriented Programming (JAVA) Review Notes (Part 2)

5. Interfaces and polymorphism

interface

An interface
, like an abstract class, defines the common attributes
of multiple classes . It makes the concept of abstraction a level deeper. It is a "pure" abstract class , which only provides one form, and does not provide the
basic implementation that allows the creator to specify the method. Form: 方法名, 参数列表and 返回类型, but not stipulated 方法主体
It can also contain data members of basic data types, but they all default to staticand final
all methods are abstract methods, and all attributes in the interface are constants.

The role of the interface
Unified development standards (specifications). The interface defines a standard , the class that uses this interface is the standard user, and the class that implements this interface is the implementer of this standard. The emergence of the interface transforms the direct connection between the user and the implementer into an indirect connection, and transforms strong coupling into weak coupling, so as to achieve the 解耦goal.
Realize multiple inheritance, and at the same time avoid the complexity of multiple inheritance in C++.
Abstract class unified development standard, but it is single inheritance

An example of an insurance company has various insurance businesses such as vehicle insurance, personal insurance, and company insurance ,
and has similarities in providing services to the outside world . A dotted line with an empty triangle indicates the syntax of an interface(premium)Insurable

insert image description here

The declaration format is

[接口修饰符] interface 接口名称 [extends 父接口名]{
    
    //方法的原型声明或静态常量
}

The data members of the interface must be assigned an initial value, and this value will not be changed again. The final keyword is allowed to be omitted. The
method in the interface must be an "abstract method" and cannot have a method body. It is allowed to omit the public and abstract keywords

Interface instance:

Interface and Anonymous Inner Class Experiment

Implementation of the interface

The interface cannot use the new operator to directly generate objects, it must use its characteristics to design a new class, and then
use the new class to create objects

public class 类名称 implements 接口名称 {
    
     
        /* Bodies for the interface methods */ 
        /* Own data and methods. */ 
}

Notice:

  1. All methods in the interface must be implemented
  2. Methods from interfaces must be declared aspublic

Object transformation
An object can be transformed into an interface type implemented by its class

For example:
getPolicyNumber, the method declared in the interface calculatePremiumis a newly added method of the Car class, and this method is not declared in the interfaceInsurable
getMileageInsurable

Car  jetta = new Car(); 
Insurable  item = (Insurable)jetta;   //对象转型为接口类型 
item.getPolicyNumber();
item.calculatePremium(); 
item.getMileage();           // 接口中没有声明此方法,不可以
jetta.getMileage();           // 类中有此方法,可以
((Car)item).getMileage(); // 转型回原类,可调用此方法了

multiple inheritance

Java is designed to be simple and practical. It does not allow a class to have multiple parent classes
, but allows a class to implement multiple interfaces. Through this mechanism, multiple inheritance can be achieved.
The syntax for a class to implement multiple interfaces is as follows

[类修饰符] class  类名称  implements 接口1,接口2,{
    
    
      … …
}

The extension of the interface
The extension of the interface
The interface can derive a new interface through the extension technology. The
original interface is called 基接口(base interface)or 父接口(super interface)
The derived interface is called 派生接口(derived interface)or 子接口(sub interface)
The derived interface can not only keep the members of the parent interface, but also add new members to meet practical problems Requirements
A class that implements an interface must also implement the interface's parent interface
Syntax for interface extensions

interface 子接口名称 extends 父接口名1,父接口名2,…
{
    
    
           … …
}

insert image description here
Shape is the parent interface, and Shape2D and Shape3D are its sub-interfaces. The Circle class and the Rectangle class implement the interface Shape2D, while the Box class and the Sphere class implement the interface Shape3D

Example:
insert image description here
insert image description here
run:
insert image description here

shape

Shaping (type-casting)
is also known as type casting
by:

隐式(自动)的类型转换
显式(强制)的类型转换

Shaped objects include
primitive data types

将值从一种形式转换成另一种形式

reference variable

将对象暂时当成更一般的对象来对待,并不改变其类型
只能被塑型为
	任何一个父类类型
	对象所属的类实现的一个接口
	被塑型为父类或接口后,再被塑型回其本身所在的类

Example:
insert image description here
Implicit (automatic) type conversion

basic data type

相容类型之间存储容量低的自动向存储容量高的类型转换

reference variable

被塑型成更一般的类
Employee  emp; 
emp = new Manager(); //将Manager类型的对象直接赋给
 //Employee类的引用变量,系统会自动将Manage对象塑
//型为Employee类

is modeled as the interface type implemented by the class to which the object belongs

Car  jetta = new Car(); 
Insurable  item = jetta; 

explicit (coerced) type conversion

basic data type

(int)871.34354;     // 结果为 871 
(char)65;              // 结果为‘A’ 
(long)453;            // 结果为453L

Reference variable: revert to original type

Employee  emp; 
Manager man;
emp = new Manager();
man = (Manager)emp; //将emp强制塑型为本来的类型

Examples of molding applications include

  1. Assignment conversion
    The expression type or object on the right side of the assignment number is converted to the type on the left side
  2. Method call conversion
    The type of the actual parameter is converted to the type of the formal parameter
  3. Arithmetic expression conversion
    During arithmetic mixed operation, items of different types are converted to the same type before operation
  4. String conversion
    During the string concatenation operation, if one operand is a string and the other is a numeric value, the numeric type will be automatically converted to a string

When a class object is shaped as its parent class, the methods it provides will be reduced.
When Managerthe object is shaped as Employee, it can only receive the method getName(), getEmployeeNumber()but not getSalary()the method .
After it is shaped as the original type, it can receive getSalary()method

If the same method is provided in both the pre-cast and post-cast classes , which class will the system call if the method is sent to the post-cast object?
There are two ways to find out according to the actual situation:

实例方法的查找
类方法的查找

Instance method lookup:

Starting from the class when the object was created, look up the class hierarchy

Manager   man = new Manager(); 
Employee  emp1 = new Employee(); 
Employee  emp2 = (Employee)man; 
emp1.computePay(); // 调用Employee类中的computePay()方法 
man.computePay(); // 调用Manager类中的computePay()方法  
emp2.computePay(); // 调用Manager类中的computePay()方法 

insert image description here
class method lookup

Lookup in the class to which the referenced variable is declared

Manager  man = new Manager(); 
Employee emp1 = new Employee(); 
Employee emp2 = (Employee)man; 
man.expenseAllowance();          //in Manager 
emp1.expenseAllowance();         //in Employee 
emp2.expenseAllowance();         //in Employee!!! 

insert image description here

polymorphism

Polymorphism means that different types of objects can respond to the same message, perform the same behavior, and exhibit different behavioral characteristics.
Multiple types derived from the same base class can be treated as the same type, and these different types can be treated in the same way. Due to polymorphism, the behavior of these different derived class objects when responding to the same method is different. difference

For example

所有的Object类的对象都响应toString()方法
所有的BankAccount类的对象都响应deposit()方法

The purpose of polymorphism
All objects can be shaped into the same type and respond to the same message
Make the code simple and easy to understand
Make the program "extensible"

Common Forms of Polymorphism
insert image description here
Prerequisites for Polymorphism

有继承/实现关系;
有父类引用指向子类对象;
有方法重写。

one example:

Drawing - direct way
If you want to be able to draw the shape of any subtype object, you can Shapedeclare several drawing methods in the class, and use different drawing methods for different actual objects

if (aShape instanceof Circle)        aShape.drawCircle(); 
if (aShape instanceof Triangle)    aShape.drawTriangle(); 
if (aShape instanceof Rectangle)  aShape.drawRectangle();

insert image description here

Drawing - a better way (polymorphism) to declare a method
with the same name in each subclass , and then drawing can be performed as followsdraw()

Shape s = new Circle(); 
s.draw();

Circle is a type of Shape, and the system will perform automatic shaping.
When the method draw is called, the binding is actually called Circle.draw()
when the program is running. Next, the concept of binding is introduced.
insert image description here
Binding refers to calling a method with the same method body Connected together
Depending on the binding period, it can be divided into

早期绑定
	程序运行之前执行绑定
晚期绑定
	也叫作“动态绑定”或“运行期绑定”
	基于对象的类别,在程序运行时执行绑定

An example:
insert image description here
insert image description here
the application of polymorphism
Technical foundation
upward shaping technology : a reference variable of a parent class can point to different subclass objects
Dynamic binding technology : execute the corresponding subclass according to the actual type of the object pointed to by the parent class reference variable at runtime method, thereby achieving polymorphism

Constructors and polymorphism
Constructors are different from other methods
Constructors are not polymorphic, but it is still very important to understand how constructors can be used with polymorphism in complex hierarchies

The order in which constructors are called

  1. Call the base class constructor
  2. Invoke member constructors in declaration order
  3. call self constructor

When constructing a derived class, it must be possible to assume that all members of the base class are valid.
Inside the constructor, all members used must be guaranteed to be initialized.
So the only way is to call the base class constructor first , and then initialize all accessible members before entering the derived class constructor

The polymorphic method in the
construction method Calling the dynamic binding method (abstract method-abstract class/interface) of the object to be constructed in the construction method
will call a method located in the derived class
The member to be manipulated by the called method may not yet be obtained Correct initialization
may cause some hard-to-find program errors

inner class

Inner class
A class defined within the definition of another class or method
Has access to all data and method members in its outer class
Can group logically related classes
Able to hide from other classes in the same package Event-driven programs
can be written very easily

Statement

命名的内部类:可在类的内部多次使用
匿名内部类:可在new关键字后声明内部类,立即创建一个对象

Assuming that the outer class name is Myclass, the inner class name of this class is

Myclass$c1.class (c1为命名的内部类名)
Myclass$1.class (表示类中声明的第一个匿名内部类)

The interface implemented by the inner class
can not be seen at all, and cannot be called,
which can facilitate the implementation of "hidden implementation details". All you get is a reference to the base class or interface

Inner class in
a method Define an inner class in a method
To implement an interface, generate and return a reference
To solve a complex problem, you need to create a class, but you don’t want it to be used by the outside world

6. I/O and files

Input and output streams (java.io)

Input stream
In order to obtain information from the information source, the program opens an input stream, and the program can read information from the input stream
Output stream
When the program needs to write information to the target location, it needs to open an output stream, and the program writes to the target location through the output stream information

The input/output flow can be classified from the following aspects:
from the direction of the flow

输入流
输出流

From the division of streams

节点流
处理流

Divide from the content of the stream

面向字符的流
面向字节的流

Character-oriented streams: used exclusively for character data
Byte-oriented streams: used for general purposes

character-oriented stream

Character-oriented stream
Optimized for the characteristics of character data, providing some useful character-oriented features
The source or destination is usually a text file

character-oriented abstract class -- ReaderandWriter

java.io包中所有字符流的抽象基类
Reader提供了输入字符的API
Writer提供了输出字符的API

Their subclasses can be divided into two categories

节点流:从数据源读入数据或往目的地写出数据
处理流:对数据执行某种处理

Most programs use a series of subclasses of these two abstract classes to read/write text information.
For example, FileReader/FileWriter is used to read/write text files.
insert image description here

byte-oriented stream

InputStreamand OutputStream
are the abstract base classes used to process 8-bit byte streams. The program uses the subclasses of these two classes to read and write 8-bit byte information. It
is divided into two parts

节点流
处理流

standard input and output stream

Standard input and output stream objects
System类的静态成员变量
include

System.in: InputStream type, representing the standard input stream, this stream has been opened, and the default state corresponds to keyboard input.
System.out: PrintStream type, representing the standard output stream, the default state corresponds to the screen output
System.err: PrintStream type, representing the standard error message output stream, the default state corresponds to the screen output

System.in
is a stream object automatically created by the Java system when the program starts. It is a primitive byte stream, and characters cannot be read directly from it. It needs to be further processed to
InputStreamReader(System.in)
createSystem.in a InputStreamReaderstream object for the parameter, which is equivalent to a byte stream. A bridge between and character streams, reading bytes and converting them to characters

BufferedReader in
Buffering of InputStreamReaderprocessed information to improve efficiency

IO exceptions
Most IO methods will throw exceptions when encountering errors, so when calling these methods, you must
declare throwing throws IOExceptionexceptions in the method header
or perform IO in the try block, and then capturecatch IOException

document

Constructs a FileWriter object given a File object.

 FileWriter(File file, boolean append)

Constructs a FileWriter object, given a filename, with a boolean indicating whether to write data appended.

FileWriter(String fileName, boolean append)

method:

public void write(int c) throws IOException

write a single character c

public void write(char [] c, int offset, int len)

Write a part of the character array that starts at offset and has a length of len

public void write(String s, int offset, int len)

Write a part of the string that starts at offset and has a length of len

Example:

Experiment 6

insert image description here

FileReader class
Reads characters from a text file
Inherited from Readerthe subclass of the abstract class InputStreamReader
BufferedReader A
buffer class for reading text files
Has readLine()a method that can identify line breaks and read the contents of the input stream line by line
Inherited from Reader

binary file

Example:

Experiment 7

insert image description here
insert image description here

FILE class

Represents disk file information
Defines some platform-independent methods to manipulate files

创建、删除文件
重命名文件
判断文件的读写权限及是否存在
设置和查询文件的最近修改时间等

Constructing a file stream can use an object of the File class as a parameter

insert image description here
Class java.io.File
Provides various useful information about files and paths
Does not open files, or process file contents
Example:

  File f1 = new File("/etc/passwd"); 
  File f2 = new File("/etc", "passwd"); 

insert image description here
The upper and lower folders are separated by delimiters:
the delimiter in Windows is \, and the delimiter in Unix/Linux is /. The more professional approach is to use the
cross-platform directory separator , and this value will be based on the corresponding separator obtained by the system.
File.separatorChar

例:new File("c:" + File.separatorChar + "a.txt");

Note:
If you use "", you need to escape and write as "\". If there are two "", write as "\\".

insert image description here
The rest of this chapter is omitted, just master the experimental content. (This part of our term exam is not the key point, so here is a lot of abbreviation, please refer to other blogs if you need it)

Seven, array collection

array of objects

First understand two kinds of sorting:
natural sorting and custom sorting

insert image description here

Arrays
Among the various methods provided by Java for storing and randomly accessing object sequences, arrays are the most efficient

类型检查
边界检查

advantage

数组知道其元素的类型
编译时的类型检查
大小已知

cost

数组对象的大小是固定的,在生存期内大小不可变

array of objects

数组元素是类的对象
所有元素具有相同的类型
每个元素都是一个对象的引用

insert image description here
A collection
is a collection of things with the same nature into a whole

Java collections cannot store basic data types , but only objects .
They are organized in a hierarchy rooted at the Collection and Map interfaces, known as the collection framework

The collection framework (Java Collections Framework) provides a unified standard architecture
for representing and manipulating collections. It provides some ready-made data structures for use. Programmers can use the collection framework to quickly write code and obtain excellent performance . It includes three chunk of content

对外的接口:表示集合的抽象数据类型,使集合的操作与表示分开
接口的实现:指实现集合接口的Java类,是可重用的数据结构
对集合运算的算法:是指执行运算的方法,例如在集合上进行查找和排序

The collection framework interface
declares general operations performed on various collection types
, including Collection, Set, List, SortedSet, Map, and SortedMap
Java collections include three types: Set(集), List(列表),Map(映射)

All Java collection classes are located java.utilin the package

Java collection framework - Collection interface

CollectionInterface
declaration can use a parameter type, that is, Collection<E>(generic type)
declares a set of abstract methods to operate batch objects: query method, modification method
query method

int size() – 返回集合对象中包含的元素个数
boolean isEmpty() – 判断集合对象中是否还包含元素,如果没有任何元素,则返回true
boolean contains(Object obj) – 判断对象是否在集合中
boolean containsAll(Collection c) –判断方法的接收者对象是否包含集合中的所有元素

Modification methods include

boolean add(Object obj) – 向集合中增加对象
boolean addAll(Collection<?> c) – 将参数集合中的所有元素增加到接收者集合中
boolean remove(Object obj) –从集合中删除对象
boolean removeAll(Collection c) -将参数集合中的所有元素从接收者集合中删除
boolean retainAll(Collection c) – 在接收者集合中保留参数集合中的所有元素,其它元素都删除
void clear() – 删除集合中的所有元素

Java collection framework - Set, SortedSet interface

Set interface
extends Collection
to prohibit repeated elements, and is an abstraction of "set" in mathematics . It has a stronger contract for sum operations. If two Set objects contain the same elements, they are equal to the
two main classes that implement it. is andequalshashCode
哈希集合(HashSet)树集合(TreeSet)

SortedSet interface
A special set
in which the elements are arranged, and related operations 升序are added. Usually used to store content such as vocabulary次序

General usage of Setinsert image description here
Example of Set:

Set<String>  set=new HashSet<String>();
String  s1=new  String(Hello);
String  s2=new  String(Hello); 
String  s3=new  String(World);
set.add(s1);
set.add(s2);
set.add(s3);
System.out.println(set.size());   //对象的数目为2

The HashSet class
The HashSet class accesses the objects in the collection according to the hash algorithm, and has good access and search performance.
When adding an object to the collection, HashSet will call hashCode()the method of the object to obtain the hash code, and then further calculate the position of the object in the collection according to the hash code.

Hash , generally translated 散列, hashed, or transliterated as hash, is to transform an input of any length into a fixed-length output through a hash algorithm , and the output is the hash value.
This transformation is a compression map , that is, the space of the hash value is usually much smaller than the space of the input.
Different inputs may hash to the same output, so it is impossible to determine a unique input value from the hash value.
The Hash algorithm is also called a hash algorithm. Although the Hash algorithm is called an algorithm, it is actually more like an idea. The Hash algorithm does not have a fixed formula, as long as the algorithm conforms to the hash idea, it can be called a Hash algorithm.

See also:
Hash

Iterator class

IterableInterface: The collection object that implements this interface supports iteration and can be used with foreach.
Iterator : an iterator, an object that provides an iteration mechanism, and how to iterate is specified by the Iterator interface. Contains three methods: hasNext, next, remove.
If the elements in the collection are not sorted, the order in which the Iterator traverses the elements in the collection is arbitrary, and may not necessarily be consistent with the order in which elements are added to the collection.

public interface Iterable<T>
{
    
    
        Iterator<T> iterator();
}

Iterator functions are relatively simple, and can only move in one direction:
the usage method iterator()requires the container to return one Iterator. The first time the method is called Iterator, next()it returns the first element of the sequence. Note: iterator()Methods belong to java.lang.Iterableinterfaces and are Collectioninherited.
Use next()to get the next element in the sequence.
Use hasNext()to check if there are more elements in the sequence.
Use to remove()remove the newly returned element from the iterator.
Iterator is the simplest implementation of Java iterator. ListIterator designed for List has more functions. It can traverse List from two directions, and can also insert and delete elements from List.

TreeSet class

The TreeSet class implements SortedSetthe interface to be able to sort the objects in the collection.
insert image description here
When an object is added to the collection, it is inserted into the ordered collection of objects.
TreeSet supports two sorting methods:

自然排序
客户化排序

Adopted by default 自然排序.

natural sort

For expressions x.compareTo(y),

如果返回值为0,则表示x和y相等
如果返回值大于0,则表示x大于y
如果返回值小于0,则表示x小于y

TreeSet calls compareTo()the method of the object to compare the size of the objects in the collection, and then arranges them in ascending order. This method is called natural sorting . Normally, it is sorted in ascending order, and you can sort in descending order the sorting methods of some classes that implement the Comparable interface in the JDK class library
by adding a negative sign in front of the return . When using natural sorting, only objects of the same type can be added to the TreeSet collection, and these objects must implement the interface.

insert image description here
Comparable

insert image description here

The custom sorting
Java.util.Comparator<Type> interface provides a specific sorting method, <Type>specifies the type of the object to be compared, and Comparatorhas a compare(Type x,Type y)method for comparing the size of two objects.
compare(x, y)

返回值为0,则表示x和y相等
如果返回值大于0,则表示x大于y
如果返回值小于0,则表示x小于y

If you want the TreeSet to be sorted in descending order according to the name attribute of the Student object, you can first create a class StudentComparator that implements the Comparator interface.
The StudentComparator class is a custom comparator.

public native int hashCode()

Returns the 32-bit jvm memory address of the object by default .
Only when creating a "class hash table", the class hashCode() is useful (the role is: to determine the position of each object of the class in the hash table;)
in other cases (for example, creating a single object of the class, or Create an array of objects of the class, etc.), the class hashCode() has no effect.
The hash table refers to the classes in the Java collection that are essentially hash tables, such as HashMap, Hashtable, and HashSet.

Take HashSet as an example to explain the function of hashCode() in depth.
insert image description hereThe relationship between hashCode() and equals()

  1. Will not create a "hash table corresponding to the class"
    insert image description here
  2. Will create a "hash table corresponding to the class"
    insert image description here

Java collection framework - List interface

The List interface
extends the Collection interface
to contain repeated elements
. The elements are ordered , and each element has a indexvalue (starting from 0) indicating the position of the element in the list.
It can be declared with a parameter, namely List<E>
four main implementation classes

Vector
ArrayList:一种类似数组的形式进行存储,因此它的随机访问速度极快
LinkedList:内部实现是链表,适合在链表中间需要频繁进行插入和删除操作
栈Stack

insert image description here
Sorting of List
List can only sort the objects in the collection according to the index order . If you want to sort the objects in the List in other specific ways, you can use Comparatorinterfaces and Collectionsclasses.
The Collections class is an auxiliary class in the Java collection class library, which provides various static methods for manipulating collections.
sort(List list): Naturally sort the objects in the List.
sort(List list,Comparator comparator): Perform custom sorting on the objects in the List, and comparatorthe parameter specifies the sorting method.

Java collection framework - Map, SortedMap interface

The Map interface
is not an inheritance of the Collection interface.
It is used to maintain key/value pairs (key/value pairs)
to describe the mapping from non-repeating keys to values. It is a mapping object from keywords to values.
There cannot be repeated keywords key. Each keyword can be mapped to at most one value.
It can be declared with two parameters, that is Map<K, V>, where K represents the type of the keyword, and V represents the type of the value .
SortedMap interface
A special Map in which the keywords are arranged in ascending order
The SortedSetequivalent Map, usually used in dictionaries and phone directories, etc.,
can be declared with two parameters, that is SortedMap<K, V>, where K represents the type of the keyword, and V represents the type of the value

Map (mapping) : Each element in the collection contains a pair of key objects and value objects. There are no repeated key objects in the collection , and value objects can be repeated .

insert image description here
When adding elements to the Map collection, a pair of key objects and value objects must be provided.
The two main implementation classes of Map: HashMapand TreeMap.

The most basic usage of Map is to provide similar 字典capabilities.
When retrieving elements in the Map, as long as it is given 键对象, it will 返回值对象.

public Set keySet(): 返回键的集合。
public Set<Map.Entry<k,v>> entrySet(): 返回“键值对”的集合。
//Map.Entry的对象代表一个“词条”,就是一个键值对。可以从中取值或键。

HashMapAccess the key-value object according to the hash algorithm.
In order to ensure HashMapthat it can work normally, and HashSetthe same, when the two key objects equals()are compared to true by the method, hashCode()the hash codes returned by the methods of the two key objects are also the same.

Detailed explanation of Map and Map.Entry
insert image description here TreeMap implements the SortedSet interface, which can sort key objects. Supports natural sorting and custom sorting.

Implementation of the interface

insert image description here

vector

Vector (Vector, ArrayList)

实现了Collection接口的具体类
能够存储任意对象,但通常情况下,这些不同类型的对象都具有相同的父类或接口
不能存储基本类型(`primitive`)的数据,除非将这些数据包裹在包裹类中
其容量能够根据空间需要自动扩充
增加元素方法的效率较高,除非空间已满,在这种情况下,在增加之前需要先扩充容量

The Vector method is synchronous, and the thread-safe
ArrayListmethod is asynchronous, which is more efficient

The Vector class can implement a dynamic array of objects. Almost the same as ArrayList.
Since Vector does not have outstanding performance in all aspects, it is not recommended to use it now .

collection traversal

Four ways of traversal
Enhance the traversal of the for loop:
insert image description here

hash table

insert image description here

Eight, thread

Multithreaded Programming Basics

Multiprogramming
stores several independent programs in the computer memory at the same time, so that they run interspersed with each other under the control of the supervisory program. A state in which two or more programs are in the same state between start and end in a computer system.

Characteristics of multiprogramming technology operation

多道
宏观上并行
微观上串行(单核CPU)

Concurrent execution of programs
The execution time of a group of logically independent programs or program segments overlaps objectively during the execution process, that is, the execution of one program segment has not yet ended, and the execution of another program segment has begun.

When the program is executed concurrently, it has the following characteristics:

间断性
失去封闭性
不可再现性

Definition of a process
A process is a running activity of a program with certain independent functions on a certain data set. It is the unit by which the operating system can allocate resources.

process characteristics

结构特征
动态性
并发性
独立性
异步性

The definition of thread
线程(thread) is the smallest unit that the operating system can perform CPU operation scheduling.
It is included in the process and is the actual operating unit in the process.
A thread refers to a single sequence of control flow in a process. Multiple threads can run concurrently in a process , and each thread performs different tasks in parallel:

减少开销
提高效率

Process : It is the basic unit for allocating and managing resources during the execution of concurrently executed programs. It is a dynamic concept and the basic unit for competing for computer system resources.
Thread : It is an execution unit of a process and the smallest unit that the operating system can perform operation scheduling. Threads are also known as lightweight processes.

A program has at least one process, and a process has at least one thread.

Why are there threads?

Each process has its own address space, that is, the process space. Under the network or multi-user switch, a server usually needs to receive a large number of concurrent requests from an uncertain number of users. It is obviously not feasible to create a process for each request (system overhead Large responses to user requests are inefficient), so the concept of threads in the operating system is introduced.

The difference between process threads:

  1. 地址空间: The threads of the same process share the address space of the process, while the address spaces between processes are independent.
  2. 资源拥有: Threads in the same process share the resources of the process such as memory, I/O, cpu, etc., but the resources between processes are independent.
  3. After a process crashes, it will not affect other processes in protected mode, but if a thread crashes, the entire process will die. So multiprocessing is more robust than multithreading .
  4. When the process is switched, it consumes a lot of resources and has high efficiency . So when it comes to frequent switching, it is better to use threads than processes. Similarly, if concurrent operations that are required to be performed at the same time and share certain variables , only threads can be used instead of processes.
  5. Execution process: Each independent process has a program running entry, sequential execution sequence and program entry. However, threads cannot be executed independently, and must depend on the application program, and the application program provides multiple thread execution control.
    Threads are the basic unit of processor scheduling, but processes are not.
  6. Both can be executed concurrently.

The three basic states of the process and their transition
insert image description here
blocking:
it is the situation where the program temporarily stops CPU occupation after running to certain functions or processes and waiting for certain events to occur; that is to say, it is a CPU idle state.

When should you consider using threads?
insert image description here
The benefits of using threads are as follows:

  1. Using threads can put the tasks in the program that take a long time into the background for processing.

  2. The user interface can be more attractive, so that for example, when the user clicks a button to trigger the processing of certain events, a progress bar can pop up to show the progress of the processing.

  3. Programs may run faster.

  4. In the implementation of some waiting tasks, such as user input, file reading and writing, and network sending and receiving data, threads are more useful. In this case, some precious resources such as memory usage and so on can be released.

  5. ……

Example:
insert image description here
insert image description here
insert image description here
The most multi-threaded scenario:

Web server Background tasks of
various dedicated servers (such as game servers) , such as sending emails to a large number of users (above 100w) at regular intervals Asynchronous processing, such as sending Weibo, recording logs, etc. Distributed computing, high-performance computing


program, process, thread

程序(Program): It is a piece of static code, which is the blueprint for application software execution.
进程(Process): It is an execution process of the program, the basic unit for the system to run the program, and the smallest unit for the system to allocate and manage resources. Multiple tasks (programs) can be run simultaneously in the operating system;
线程(Thread): It is an execution unit smaller than a process, equivalent to an execution path in a task, and the smallest unit of system operation scheduling. There are multiple sequence flows executing concurrently in the same application.

The purpose of multithreading is to maximize the use of CPU resources .

There are two ways to implement multithreading in Java:

  1. Inherit the classes java.langin the package Thread.
  2. Users implement the interface in classes that define themselves Runnable.

Inherit the Thread class in the java.lang package

Thread类It directly inherits the Object class and implements Runnablethe interface. Located java.langin the package
Encapsulates the properties and methods required by the thread object
Inheritance Threadclass - one of the methods to create multi-threading Derived a subclass
from Threadthe class, and create an object of the subclass The subclass
should override the method Threadof the class run, and the write needs to be in the new The statement segment executed in the thread.
Calling starta method to start a new thread automatically enters runthe method.

Define a subclass of Thread and override its run method such as:

class MyThread extends Thread {
    
    
         @Override
            public void run() {
    
    ...}
 }

Create an object of this class:

MyThread myThread = new MyThread();

Start or run the thread, and the Java virtual machine will automatically start the thread, so that the Java virtual machine can further uniformly schedule the threads, so that all threads can run concurrently together.

public void start()
myThread.start();

Example:

public class ThreadCreateDemo1 {
    
    
    public static void main(String[] args) {
    
    
        MyThread thread = new MyThread();
        thread.start(); //该方法调用多次,出现IllegalThreadStateException
    }
}

class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        super.run();
        System.out.println("hellow_world!");
    }
}

Implement the Runnable interface

The Runnable interface
Thread类implements Runnablethe interface
. There is only one run() method,
which is more convenient for multiple threads to share resources
. Java does not support multiple inheritance. If you have inherited a certain base class, you need to implement the Runnable interface to generate multiple threads.
The object that implements runnable is established as a parameter. The new thread
startmethod starts the thread and runs run()the method

Example:

public class ThreadCreateDemo2 {
    
    
    public static void main(String[] args) {
    
    
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

class MyRunnable implements Runnable {
    
    
    public void run() {
    
    
        System.out.println("通过Runnable创建的线程!");
    }
}

The difference between inheriting Thread and implementing the Runnable interface:

a.实现Runnable接口避免多继承局限
b.实现Runnable()可以更好的体现共享的概念

Data Sharing Between Threads

Create multiple threads with the same Runnableobject that implements the interface as a parameter Multiple threads
share the same data in the same object

Independent concurrently running threads sometimes need to share some data and take into account each other's state and actions . In this way, there is a problem of mutual interference data (shared data error)

concurrent programming

Multi-threaded synchronization control

Sometimes threads are not independent of each other and need to be synchronized

mutual exclusion between threads

同时运行的几个线程需要共享一个(些)数据
共享的数据,在某一时刻只允许一个线程对其进行操作

The "producer/consumer" problem

假设有一个线程负责往数据区写数据,另一个线程从同一数据区中读数据,两个线程可以并行执行
如果数据区已满,生产者要等消费者取走一些数据后才能再写
当数据区空时,消费者要等生产者写入一些数据后再取

Thread synchronization Synchronization
互斥 : Many threads operate on the same shared data without interfering with each other, and only one thread can access the shared data at the same time. Therefore, some methods or program segments can only be executed by one thread at the same time, which is called a monitor area (critical area) .
协作: Multiple threads can conditionally operate on shared data concurrently. The thread executing the code in the monitor area can allow other threads to enter the monitor area if the conditions are met.

The multithreaded thread synchronization mechanism is actually controlled by the concept of locks .

Multi-threaded lock synchronization mechanism

insert image description here
对象锁. Lock the object, and the locks of different instances do not affect each other.

  1. Decorate instance methods with synchronized
  2. Decorate code blocks with synchronized

类锁. The objects all share the same lock and are executed synchronously. Only when one thread finishes executing can other object threads be able to call the synchronized part. Different class locks do not affect each other.

  1. Decorate static methods with synchronized
  2. Decorate code blocks with synchronized

Two forms of object locks: (note synchronized)

public class Test
{
    
    
    // 对象锁:形式1(修饰实例方法)
    public synchronized void Method1()
    {
    
    
        System.out.println("我是对象锁也是方法锁");
        try
        {
    
    
            Thread.sleep(500);
        } catch (InterruptedException e)
        {
    
    
            e.printStackTrace();
        }

    }

    // 对象锁:形式2(修饰代码块)
    public void Method2()
    {
    
    
        synchronized (this)
        {
    
    
            System.out.println("我是对象锁");
            try
            {
    
    
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
    
    
                e.printStackTrace();
            }
        }

    }

class lock:

insert image description here

public class Test
{
    
    
   // 类锁:形式1
    public static synchronized void Method1()
    {
    
    
        System.out.println("我是类锁一号");
        try
        {
    
    
            Thread.sleep(500);
        } catch (InterruptedException e)
        {
    
    
            e.printStackTrace();
        }

    }

    // 类锁:形式2
    public void Method()
    {
    
    
        synchronized (Test.class)
        {
    
    
            System.out.println("我是类锁二号");
            try
            {
    
    
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
    
    
                e.printStackTrace();
            }

        }

    }

Java uses the monitor mechanism.
There is only one object for each object , and the mutual exclusion between threads is realized by the competition of 锁旗标multi-thread pairs. When thread A obtains the lock flag of an object, thread B must wait for thread A to complete the specified operation and release After the lock flag is locked, the lock flag of the object can be obtained and the operation in thread B can be performed锁旗标

Put the statement segment that needs to be mutually exclusive into synchronized(object){}the statement, and the objects in the two places are the same

communication between threads

insert image description here
In order to coordinate the work of different threads more effectively, it is necessary to establish a communication channel between threads, and solve the synchronization problem between threads through "dialogue" between threads. Some methods of this class provide effective means for communication between threads. If the current state is
java.lang.Object not
wait() suitable This thread executes, a thread A that is executing the synchronization code ( synchronized) calls this method (on object x), the thread suspends execution and enters the waiting pool of object x, and releases the lock flag of object x that has been acquired. notifyThread A has to wait until other threads call or method on object x notifyAllbefore it can regain the lock flag of object x and continue execution (continue execution after the wait statement)

notify() Randomly wake up a waiting thread, and
the thread continues to execute. After the thread is woken up, it has to wait for the person who sends the wakeup message to release the monitor. During this period, the key data may still be changed.
When the awakened thread starts to execute, it is necessary to judge whether the current state is suitable. Run by yourself
notifyAll() to wake up all waiting threads, and this thread will continue to execute

Detailed explanation of wait, notify/notifyAll

insert image description here
insert image description here
To test the change of a certain condition in multithreading, use if or while?

insert image description here
Obviously, only when the current value meets the required value, the thread can execute down, so the while loop must be used to block . Note that wait()when awakened, just let the while loop continue to go down. If if is used here, it means that if continues to go down, it will jump out of the if statement block. However, notifyAll it is only responsible for waking up the thread, and does not guarantee the conditions, so it is necessary to manually ensure the logic of the program.

thread deadlock

Blocking: Pausing the execution of a thread to wait for a condition to occur.
IO blocking:

DatagramSocket.recive(); ServerSocket.recive()

thread blocking

synchronized(obj)等待obj解锁;
wait(),等待其他线程的notify()

Critical Resources
In a multiprogrammed system there are many processes that share various resources, but there are many resources that can only be used by one process at a time. Resources that are only allowed to be used by one process at a time are called critical resources. Many physical devices are critical resources, such as input machines, printers, tape drives, and so on.
Each process adopts a mutually exclusive method, and the shared resources are called critical resources.
The hardware belonging to critical resources includes printers, tape drives, etc., and the software includes message buffer queues, variables, arrays, buffers, etc.
The section of code in each process that accesses critical resources is called
a critical section
. Obviously, if it can be ensured that all processes enter their own critical section exclusively, the mutually exclusive access of all processes to critical resources can be realized .

Deadlock
Multiple threads are blocked at the same time, one or all of them are waiting for a resource to be released. Since the thread is blocked indefinitely, it is impossible for the program to terminate gracefully.

Four necessary conditions:

互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
循环等待,即存在一个等待队列:
		P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。

one example:
insert image description here

avoid deadlock

sychronized
Semaphore Semaphore
is a counting semaphore. Conceptually, a semaphore maintains a set of permissions. If necessary, each one blocks until a permit is available acquire(), and then acquires that permit. Each release()adds a permit, potentially releasing a blocking acquirer. However, the actual license object is not used,
Semaphoreonly the number of available licenses is counted and acted accordingly. The thread that gets the semaphore can enter the code, otherwise it waits. Pass acquire()and release()Acquire and Release Access Permissions.

Critical resources : resources that can only be used exclusively (mutually exclusive) at a certain moment, and allow multiple people to share at different times.
example:

The company's bank account is authorized by the company to deposit and withdraw money from multiple people, but only one person is allowed to deposit and withdraw at a time.
Products such as mobile phones are first produced by producers and then sold to consumers. A product cannot be in production and consumption at the same time.

Thread synchronization and mutual exclusion: dealing with critical resources, involving mutual cooperation between multiple threads (step coordination).
synchronized锁定方法, like adding a "lock" to critical resources, so that the method execution process can "synchronize" (cooperate with good steps) on critical resources.
synchronizedLock critical resources, syntax:

synchronized( 临界资源对象 ){
    
     操作代码 } 

The producer and consumer model
(1) has a warehouse with a certain capacity for storing products.
(2) Producers continue to produce products, and products are stored in warehouses (product storage).
(3) Consumers continue to buy products in the warehouse (product out of warehouse).
(4) Only when there is space in the warehouse can producers produce, otherwise they can only wait.
(5) Consumers can purchase (consume) only if there are products in the warehouse.

In the producer and consumer model, four concepts are involved: 产品, 仓库, 生产者and 消费者, the key is the latter three:

仓库,是临界资源,仓库的产品不能同时入仓和出仓。
生产者线程:工人。
消费者线程:购买产品的人。

In the real world, many problems can be attributed to the producer-consumer model, such as the deposit and withdrawal operations of a company's bank account. The bank account is equivalent to a massive warehouse, and there is no limit to the production (deposit) capacity.

insert image description here

background thread

Background thread,
also called daemon thread, is usually a thread that runs to assist other threads.
It does not prevent the program from terminating
as long as there is one foreground thread running in a process, the process will not end; if all the foreground threads in a process are It has ended, so no matter whether there are unfinished background threads, this process will end.
"Garbage collection" is a background thread.
If a setDaemon(true)method is called on a thread object before it is started (calling the start method), the thread becomes background thread

There are two types of threads in Java: User Thread(用户线程),Daemon Thread(守护线程)

User thread : The thread running in the foreground, also called ordinary thread, only completes the tasks that the user wants to complete, and does not provide public services.

insert image description here
Create an infinite loop background thread, verify that the program ends after the main thread ends.
Run the program, and find that the entire program stops running when the main thread ends. If t.setDaemon(true)the statement is commented out, the program will never end
insert image description here

thread lifetime

The life cycle of a thread
is the process from generation to death of
a thread. A thread is in a certain thread state (thread state) at any time.

insert image description here
insert image description here

control thread life

end thread life

Use stopthe method to end the life of the thread
, but if a thread is operating the shared data segment, if the operation process is not completed and the stop is used to end, the data will be incomplete, so this method is not recommended

Usually, a thread can be terminated by controlling the loop condition in the run method

thread priority

Thread scheduling
In a single-CPU system, multiple threads need to share the CPU, and only one thread can actually run at any point in time

Controlling multiple threads to run in a certain order on the same CPU is called thread scheduling

The Java virtual machine supports a very simple, deterministic scheduling algorithm called the fixed-priority algorithm . This algorithm schedules threads based on their priority

Thread Priority
Each Java thread has a priority which ranges 1和10between. By default, the priority of each thread is set to 5. A
new thread object B created during the running of thread A has the same priority as thread A in its initial state.
If A is a background thread, B is also a background thread. At any time
after the thread is created , its original priority can be changed through the methodsetPriority(int priority)

Thread scheduling based on thread priority
Threads with higher priority are executed prior
to threads with lower priority For threads with the same priority, Java's processing is random, and the
underlying operating system may support fewer than 10 priorities , which can cause some confusion. Therefore, use priority only as a rough tool. The final control can be done by judicious use of the yield() function.
We can only use thread priority based on efficiency considerations, and cannot rely on thread priority to ensure the correctness of the algorithm.

Assuming that a thread is running, it will be suspended only if one of the following conditions occurs

  1. A thread with a higher priority becomes ready (Ready);
  2. Due to input/output (or some other reasons), calls to sleep, wait, yield methods make it blocked;
  3. For systems that support time slicing, the time slice's time expires

Guess you like

Origin blog.csdn.net/qq_51594676/article/details/125240334