Summary of popular JAVA interview questions and answers on the whole network | The first part of Java basic knowledge points

Article directory

Java Basic Outline

insert image description here

Interview data download (key)

1. To obtain the PDF of this chapter , please reply " java-01 " on the WeChat public account [IT Senior]

2. To obtain the complete Java interview materials , please reply " java-pdf " on the WeChat public account [IT seniors] . The interview materials include:

  • Part 1: Java Basics
  • Part Two: JavaWeb
  • Part III: Java Advanced Framework
  • Part IV: Microservice Distributed
  • Part V: Algorithm Structure and Algorithm Topics
  • Part VI: Interview Guidance, Scenario Questions

1. What kind of language is Java, and the difference between JDK, JRE, and JVM?

Java is a completely object-oriented programming language, which has the characteristics of simplicity, object-oriented, distributed, robustness, security, platform independence and portability, multi-threading, and dynamics. It absorbs the advantages of C++ and removes the Understand the concepts that are difficult to understand such as multiple inheritance and pointers in C++. The java language adopts the Unicode encoding standard.

JDK (Java Development Kit) is a product for Java developers. It is the core of the entire Java, including the Java runtime environment JRE, Java tools, and Java basic class libraries.

Java Runtime Environment (JRE) is a collection of environments necessary to run JAVA programs, including JVM standard implementation and Java core class library.

JVM is the abbreviation of Java Virtual Machine (Java Virtual Machine), which is the core part of the entire Java cross-platform implementation, and can run software programs written in the Java language.

The relationship between jvm, jre and jdk

2. What are the three major versions after Java 1.5?

  • Java SE Java Standard Edition
  • Java EE Java Enterprise Edition
  • Java ME Java Micro Edition

3. Java cross-platform and its principle?

The so-called cross-platform means that after the Java source code is compiled once, it can run on different operating systems.

Principle: The compiled .class file runs on the Java virtual machine, not directly on the operating system, as long as the JVM (JAVA virtual machine) that meets different operating systems is installed.

4. What are the characteristics of the Java language?

  1. object-oriented. Java is an object-oriented language, which satisfies the basic characteristics of object-oriented (encapsulation, inheritance, polymorphism)
  2. Cross-platform. JVM realizes the cross-platform of Java language
  3. Support network programming
  4. Support multithreading
  5. robustness. Strong type mechanism of Java language, exception handling mechanism, GC automatic garbage collection mechanism

5. What is bytecode and the benefits of bytecode?

  • Bytecode: The .class file generated by Java through the Javac command is bytecode
  • Benefits of bytecode:
  1. Solve the problem of inefficiency of interpreted language to some extent
  2. Not targeting a specific machine, preserving the portability of interpreted languages

6. What is the difference between Java and C++?

Both Java and C++ are object-oriented languages. Therefore, there are object-oriented basic features of encapsulation, inheritance, and polymorphism. Their differences are as follows:

  1. Java does not provide pointers to directly access memory, program memory is safer
  2. Single inheritance in Java, multiple inheritance in C++
  3. There is a memory management mechanism in Java, which does not require programmers to manually release memory

7. What are the three main features of Java?

  • Encapsulation: Encapsulate methods and variables in classes to improve code security
  • Inheritance: Single inheritance in Java improves code reusability
  • Polymorphism: Polymorphism is the same class or interface, using different instances to perform different operations, improving code flexibility

8. What are the basic data types and reference data types in Java and their differences?

  • 8 basic data types
illustrate Occupied memory size (bytes) Ranges Defaults
byte The smallest data type in Java 1 − 2 7 {-2^7} 27~ 2 7 {2^7} 27-1 0
short short integer 2 − 2 15 {-2^{15}} 215~ 2 15 {2^{15}} 215-1 0
int integer 4 − 2 31 {-2^{31}} 231~ 2 31 {2^{31}} 231-1 0
long long integer 8 − 2 63 {-2^{63}} 263~ 2 63 {2^{63}} 263-1 0L
float single precision 4 -3.40E+38 ~ +3.40E+38 0
double double precision 2 -1.79E+308 ~ +1.79E+308 0
char character type 2 0~65535 null
boolean Boolean 1 true,false false
  • reference data type

class, interface type, array type, enumeration type, annotation type

  • The difference between primitive data types and reference data types

When the basic data type is created, it will allocate space on the stack and store it directly in the stack. When a reference data type is created, it will first allocate space on the stack, store its reference in the stack space, and then open up memory in the heap. The value is stored in the heap memory, and the reference in the stack points to the address in the heap.

9. switch(expr), what data types does expr support?

Before Java5, expr supported four data types: byte, short, int, and char. After Java5, an enumeration enum type was added, and Java7 added a string type. So far, it does not support the long type.

10. What is the difference between int and Integer? How to understand automatic unboxing and automatic boxing?

int is a basic data type, the default value is 0
integer is a reference type, a wrapper class for int, and the default value is null

Automatic unboxing: Automatically convert the packaging type into the corresponding basic data type
Automatic boxing: Automatically convert the basic type into the corresponding reference type

11. What is the most efficient way to calculate 2^3?

The most efficient way to calculate 2^3 is: 2<<(3-1)

12、Math.round(temp) ?

The principle of rounding is to add 0.5 to the original parameter, and then round down.

13. Is float f=3.4; correct?

Incorrect. 3.4 is a double-precision type, and assignment to float requires forced type conversion, float f=(float)3.4, which can be written as float f=3.4F.

14. Short s1 = 1; s1 = s1 + 1; Is it wrong?

short s1 = 1; s1 = s1 + 1 is incorrect. Because 1 is an int type, s1+1 is also an int type. When executing s1=s1+1, you need to assign the int type s1+1 to the short type s1. There may be a loss of precision when converting from large to small, and the conversion cannot be displayed. .

15. Is short s1 = 1; s1 += 1; wrong?

short s1 = 1; s1 += 1 is correct. Since s1+=1 is equivalent to s1=(short)(s1+1), there is an implicit cast.

16. Comments in Java?

Definition: A comment is a text used to explain a program. Divided into:

  • Single-line comment: // Text of the comment
  • Multi-line comment: /* text of comment */
  • Documentation comment: /** text of comment **/

17. What are the access modifiers in Java?

The access modifiers in Java are: public, private, protected, and not written (default).

18. What is the difference between rewriting and overloading?

Rewriting: Occurs in at least two classes, and the class has an inheritance or implementation relationship with the class, which means that the method in the subclass has exactly the same method name, return value, and parameters as the method in the parent class. The method in the subclass overrides the method of the parent class, which reflects polymorphism.

Overloading: Occurs in the same class, multiple methods with the same name, different parameter types, numbers and order overloading occurs, and has nothing to do with the return value.

19. What is the difference between operator & and &&?

&: Regardless of whether the left side is true or false, the right side will also be judged.
&&: If the left side is false, no judgment will be made if there is an edge, so && is more efficient than &.

Note: The same is true for the difference between the logical OR operator (|) and the short-circuit OR operator (||).

20. Does Java have goto?

goto is a reserved word in Java and is not used in the current version of Java.

21. What is the usage of this keyword?

  1. For ordinary direct references, this is equivalent to pointing to the current object itself.
  2. The name of the formal member has the same name, use this to distinguish:
public Person(String name, int age) {
    
    
    this.name = name;
    this.age = age;
}
  1. Call the constructor of this class:
class Person{
    
    
    private String name;
    private int age;
    
    public Person() {
    
    
    }
 
    public Person(String name) {
    
    
        this.name = name;
    }
    public Person(String name, int age) {
    
    
        this(name);
        this.age = age;
    }
}

22. What is the usage of the super keyword?

  1. Ordinary direct quotes.
  2. Call the method in the parent class with the same name as the subclass.
  3. Call the constructor of the parent class.

23. Java's final keyword?

In java, the final keyword can modify classes, variables and methods. After being modified by final, the following characteristics:

  • Final modified class: final modified class cannot be inherited.
  • Final modified variables: Final modified variables are constants and cannot be changed.
  • Final modified method: The final modified method cannot be overridden.

24. What are the differences and functions of break, continue, and return?

  • break: break out of the current loop
  • continue: End this cycle and proceed to the next cycle
  • return: return

25. In Java, how to jump out of the current multiple nested loops?

Define a label before the outer loop statement

ok:
for(int i=0;i<10;i++){
    
    
     for(int j=0;j<10;j++){
    
    
       system.out.println("i="+i+",j="+j);
       if(j==5)break ok;
    }
}

26、hashCode 与 equals?

If the equals() methods of two objects are equal, their hashCode return values ​​must be the same. If the hashCode return values ​​of two objects are the same, their equals() methods are not necessarily equal.

If the return values ​​of hashCode() of two objects are equal, it cannot be judged that the two objects are equal, but if the return values ​​of hashCode() of two objects are not equal, it can be judged that the two objects must not be equal.

27. What is the difference between an abstract class and an interface?

The methods in the interface are all abstract, and the abstract class can have abstract methods or non-abstract methods.

After JDK1.8, the interface can also use the common method modified by the defaule keyword

28. What is an interface?

Interface is a specification, interface in Java: interface

29. The difference between static variables and non-static variables

static variable non-static variable
calling method Static variables can only be called by "class name. variable name" Non-static variables are called by instantiating the object name
sharing method Static variables are global variables, shared by all instantiated objects of the class Non-static variables are local variables, not shared
Mutual access method Static variables cannot access non-static variables Non-static variables can access static variables

30. What is the difference between passing by value and passing by reference?

Value transfer: In the process of calling the method, the actual parameter passes its actual value to the formal parameter. This transfer process is to copy the value of the actual parameter and pass it to the function.

Passing by reference: Passing by reference makes up for the deficiency of passing by value. If the amount of data passed is large, if it is copied directly, it will take up a lot of memory space, and passing by reference is to pass the address value of the object to the past, and the function receives the original value. The initial address value of . During the execution of the method, the content of the formal parameter and the actual parameter are the same, pointing to the same memory address, which means that the operation is actually source data, so the execution of the method will affect the actual object.

31. What is reflection?

The JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties.

32. What are the commonly used methods in the String class?

method illustrate
split() Split a string into an array of strings
indexOf() Extract the index position from the specified character
append() Append a character or string
trim() Remove spaces from both ends of a string
replace() replace
hashCode() Returns the hash value of a string
subString() intercept string
equals() compare strings for equality
length() get string length
concat() concatenates the specified string to the end of this string

33. What is the difference between == and equals in String?

"==" compares the memory addresses of the two strings. "equals" compares the actual values ​​of the two strings

34. What is the difference between String, StringBuilder and StringBuffer in Java?

String: String constant, the bottom layer is decorated with the final keyword, and the bottom layer is actually maintaining a character array of char type. When changing the String every time, a new String object needs to be generated, and then the pointer points to a new object.

//底层用 final 关键字修饰,底层实际在维护 char 类型的字符数组
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
    
    
    /** The value is used for character storage. */
    private final char value[];
    }

StringBuilder: string variable, thread-safe, for multi-threaded operation

StringBuffer: string variable, not thread-safe, for single-threaded operation

35. What is the difference between final, finally and finalize in Java?

final: Modifier, keyword in java. It can be used to modify classes, variables, methods, and has a final meaning.

modified object illustrate
final modified class Indicates that this class cannot be inherited by other classes, but be careful: all member methods in the final class will be implicitly defined as final methods.
final modifier variable The final member variable represents a constant, which can only be assigned once, and its value will not change after assignment
final modification method Final modified methods cannot be overridden

finally: finally is often used in exceptions. It is the method that must be executed after the code in try and cach is executed. We often write some methods to close resources in finally, such as closing database connections or closing IO flow.

finalize: finalize is the method name, and Java technology allows the use of the finalize() method to do the necessary cleanup before the garbage collector clears the object from memory.

36. Can there be multiple inheritance in Java?

Multiple inheritance is not allowed in Java. For example, class A cannot inherit class B and class C at the same time. If there are subclass requirements, consider using interfaces.

37. What is the difference between HashMap and Hashtable?

HashMap and Hashtable are the implementation classes of the Map interface. They generally have the following differences:

  1. The inherited parent class is different. HashMap is inherited from the AbstractMap class, and HashTable is inherited from the Dictionary class.
  2. Thread safety is different. The methods in Hashtable are Synchronized, while the methods in HashMap are non-Synchronized by default. Hashtable is out-of-the-box safe, and HashMap is not thread-safe.
  3. Whether the key and value allow null values. In Hashtable, null values ​​are not allowed for key and value. But if there is an operation like put(null,null) in Hashtable, the compilation can also pass, because the key and value are both Object types, but a NullPointerException will be thrown at runtime, which is stipulated by the JDK specification. In HashMap, null can be used as a key, and there is only one such key; there can be one or more keys whose corresponding value is null. When the get() method returns a null value, it may be that the key does not exist in the HashMap, or the value corresponding to the key may be null. Therefore, in the HashMap, the get() method cannot be used to judge whether a certain key exists in the HashMap, but the containsKey() method should be used to judge.

38. What are the implementation classes of the Map collection, and what are their characteristics?

Implementation class feature
HashMap A collection of thread-unsafe key-value pairs, allowing null values, both key and value
HashTable A thread-safe collection of key-value pairs, null values ​​are not allowed, neither key nor value is allowed
TreeMap Ability to sort the records it saves according to the key, the default is sorted in ascending order

39. Solve the problem of hashmap thread insecurity?

  1. Collections.synchronizedMap() method
  2. java.util.concurrent.ConcurrentHashMap 类

40. What is the underlying implementation principle of Hashmap?

In JDK1.6 and JDK1.7, HashMap is implemented by bit bucket + linked list, that is, a linked list is used to handle conflicts, and key-value pairs with the same hash value will be placed in the same bit bucket. When there are many elements in the bucket, the key Value lookups are less efficient.

In JDK1.8, HashMap is implemented using bit bucket + linked list + red-black tree. When the length of the linked list exceeds the threshold (8), the linked list is converted into a red-black tree, which greatly reduces the search time.

当我们创建 hashmap 时 会先创建一个数组,当我们用 put 方法存数据时,先根据 key 的 hashcode 值计算出 hash 值,然后用这个哈希值确定在数组中的位置,再把 value 值放进去,如果这个位置本来没放 东西,就会直接放进去,如果之前就有,就会生成一个链表,把新放入的值放在头部,当用 get 方法取值时,会先根据 key 的 hashcode 值计算出 hash 值,确定位置,再根据 equals 方法从该位置上的链表中取出该 value 值。

41、hash 碰撞怎么产生,怎么解决?

对象Hash的前提是实现equals()和hashCode()两个方法,那么HashCode()的作用就是保证对象返回唯一hash值,但当两个对象计算值一样时,这就发生了碰撞冲突。如下将介绍如何处理冲突,当然其前提是一致性hash。

解决hash碰撞有以下几种方法:

  • 开放地址法

开放地执法有一个公式:Hi=(H(key)+di) MOD m i=1,2,…,k(k<=m-1) 其中,m为哈希表的表长。di 是产生冲突的时候的增量序列。如果di值可能为1,2,3,…m-1,称线性探测再散列。如果di取1,则每次冲突之后,向后移动1个位置.如果di取值可能为1,-1,2,-2,4,-4,9,-9,16,-16,…kk,-kk(k<=m/2),称二次探测再散列。如果di取值可能为伪随机数列。称伪随机探测再散列。

  • 再哈希法

当发生冲突时,使用第二个、第三个、哈希函数计算地址,直到无冲突时。缺点:计算时间增加。比如上面第一次按照姓首字母进行哈希,如果产生冲突可以按照姓字母首字母第二位进行哈希,再冲突,第三位,直到不冲突为止。

  • 链地址法(拉链法)

将所有关键字为同义词的记录存储在同一线性链表中。如下:

42、HashMap 为什么需要扩容?

当hashmap中的元素个数超过数组大小的loadFactor倍时,就会进行数组扩容,loadFactor的默认值为 0.75,也就是说,默认情况下,数组大小为 16,那么当hashmap 中元素个数超过 16*0.75=12 的时候,就把数组的大小扩展为2*16=32,即扩大一倍。然后重新计算每个元素在数组中的位置,而这是一个非常消耗性能的操作,所以如果我们已经预知 hashmap 中元素的个数,那么预设元素的个数能够有效的提高 hashmap 的性能。比如说,我们有 1000 个元素new HashMap(1000), 但是理论上来讲 new HashMap(1024)更合适,不过上面annegu 已经说过,即使是 1000,hashmap 也自动会将其设置为 1024。 但是newHashMap(1024)还不是更合适的,因为 0.75*1000<1000,也就是说为了让0.75*size>1000, 我们必须这样 newHashMap(2048)才最合适,避免了resize 的问题。

43、如何遍历 Map 集合?

  1. 先获取 Map 中的 key 的 set 集合 map.keySet(); 通过遍历 key 集合,获取 value 值。
  2. Map.get(key)先获取 Entry 集合 map.entrySet(); 遍历 entrySet 分别获取 key value。

44、ArrayList 与 LinkedList 区别?

ArrayList 使用数组方式存储数据,所以根据索引查询数据速度快,而新增或者 删除元素时需要设计到位移操作,所以比较慢。

LinkedList 使用双向链接方式存储数据,每个元素都记录前后元素的指针, 所以插入、删除数据时只是更改前后元素的指针指向即可,速度非常快,然后通过下标查询元素时需要从头开始索引,所以比较慢,但是如果查询前几个元素或 后几个元素速度比较快。

ArrayList 与 LinkedList 都是线程不安全的。

45、Java中的ArrayList的初始容量和容量分配?

ArrayList是经常会被用到的,一般情况下,使用的时候会像这样进行声明:

List arrayList = new ArrayList();

如果像上面这样使用默认的构造方法,初始容量被设置为10。当ArrayList中的元素超过10个以后,会重新分配内存空间,使数组的大小增长到16。

可以通过调试看到动态增长的数量变化:10->16->25->38->58->88->…

也可以使用下面的方式进行声明:

List arrayList = new ArrayList(4);

将ArrayList的默认容量设置为4。当ArrayList中的元素超过4个以后,会重新分配内存空间,使数组的大小增长到7。

可以通过调试看到动态增长的数量变化:4->7->11->17->26->…

那么容量变化的规则是什么呢?请看下面的公式:

((旧容量 * 3) / 2) + 1

46、如何使用的 List 集合来保证线程安全?

  1. 使用 Vector

  2. 使用 Collections 中的方法 synchronizedList 将 ArrayList 转换为线程安全的 List

  3. 使用 java.util.current 包下的 CopyOnWriteArrayList(推荐)

47、IO 和 NIO 的区别?

这个NIO是JDK1.7以后有的,它们俩的主要区别是 :

  1. IO是面向流是阻塞IO,NIO是面向缓冲,非阻塞的 IO;
  2. IO话每次从流中读取一个多个字节,直到读取完所有的字节 ,没有缓存到任何地方。NIO读取的是数据是有缓存的,就是说他读取的数据是在缓冲里读的。
  3. 另外的话,Java中的各种IO是阻塞的。就是说一个线程调用 read 或 者 write()时,这个线程就已经被阻塞了,直到读取到一些数据为止,或者是完全写入。在这个过程中不能干其他的事情。NIO的非阻塞模式 ,当发送一个读取数据的请求的时候 ,如果没有读取到可用的数据,就什么也不会获取,且不会让线程阻塞。
  4. 非阻塞的IO的空闲时间可用用来做其他的,操作所以,一个单独的非阻塞线程可以管理 多个输入和输出通道,另外 NIO 还有一个selector(选择器),它是可以管理多个输入输出的通道。

48、在 Java 中要想实现多线程代码有几种手段?

  1. 一种是继承 Thread 类
  2. 另一种就是实现 Runnable 接口
  3. 最后一种就是实现 Callable 接口
  4. 第四种也是实现 callable 接口,只不过有返回值而已

49、Thread 类中的 start() 和 run() 方法有什么区别?

start()方法被用来启动新创建的线程,而且 start()内部调用了 run()方法,这和直接调用 run()方法的效果不一样。当你调用 run()方法的时候,只会是在原来的线程中调用,没有新的线程启动,start()方法才会启动新线程。

50、Java 中 notify 和 notifyAll 有什么区别?

notify()方法不能唤醒某个具体的线程,所以只有一个线程在等待的时候它
才有用武之地。而 notifyAll()唤醒所有线程并允许他们争夺锁确保了至少有一
个线程能继续运行。

51、Java 多线程中调用 wait() 和 sleep()方法有什么不同?

Java 程序中 wait 和 sleep 都会造成某种形式的暂停,它们可以满足不同的需要。wait()方法用于线程间通信,如果等待条件为真且其它线程被唤醒时它会释放锁,而 sleep()方法仅仅释放 CPU 资源或者让当前线程停止执行一段时间,但不会释放锁。

52、什么是线程安全

多个线程同时运行一段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。同一个实例对象在被多个线程使用的情况下也不会出现计算失误,也是线程安全的,反之则是线程不安全的。

53、Java中的 volatile 变量是什么?

Volatile: 一个共享变量(类的成员变量、类的静态成员量)被volatile修饰之后,那么就具备了两层语义:

  • a.保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。

  • b.禁止进行指令重排序。但是它并不能保证操作的原子性。

应用场景:在只涉及可见性,针对变量的操作只是简单的读写(保证操作的原子性)的情况下可以使用volatile来解决高并发问题,如果这时针对变量的操作是非原子的操作,这时如果只是简单的i++式的操作,可以使用原子类atomic类来保证操作的原子性(采用CAS实现),如果是复杂的业务操作,那么舍弃volatile,采用锁来解决并发问题(synchronized或者Lock)。

54、线程的状态?

实线程一般具有五种状态,即创建、就绪、运行、阻塞、终止。

insert image description here

  1. 新建( new ):新创建了一个线程对象。
  2. 可运行( runnable ):线程对象创建后,其他线程(比如 main 线程)调用了该对象的start ()方法。该状态的线程位于可运行线程池中,等待被线程调度选中,获 取 cpu 的使用权 。
  3. 运行( running ):可运行状态( runnable )的线程获得了 cpu 时间片( timeslice ),执行程序代码。
  4. 阻塞( block ):阻塞状态是指线程因为某种原因放弃了 cpu 使用权,也即让出了 cpu timeslice ,暂时停止运行。直到线程进入可运行( runnable )状态,才有机会再次获得 cpu timeslice 转到运行( running )状态。阻塞的情况分三种:
  • a.等待阻塞:运行( running )的线程执行 o.wait ()方法,JVM 会把该线程放 入等待队列( waitting queue )中。

  • b.同步阻塞:运行( running )的线程在获取对象的同步锁时, 若该同步锁被别的线程占用,则 JVM 会把该线程放入锁池( lock pool )中。

  • c.其他阻塞: 运行( running )的线程执行 Thread . sleep ( long ms )或 t.join ()方法,或者发出了 I / O 请求时,JVM 会把该线程置为阻塞状态。当 sleep ()状态超时、 join ()等待线程终止或者超时、或者 I / O 处理完毕时,线程重新转入可运行( runnable )状态。

  1. 死亡( dead ):线程 run ()、 main () 方法执行结束,或者因异常退出了 run ()方法,则该线程结束生命周期。死亡的线程不可再次复生。

55、实现线程同步有三种方式?

  1. 同步代码块:在代码块上加上“synchronized”关键字的话,则此代码块就称为同步代 码块。
//同步代码块格式: 
synchronized(监视对象){
    
    
 //需要同步的代码 ;
}

解释:监视对象有三种:对象、String、.class 文件(只要是不变的对象都可以做监 视对象)

  1. 同步方法
//同步方法定义格式: 
synchronized 方法返回值 方法名称(参数列表){
    
    
}
//在方法上加 synchronized,是把当前对象做为监视器
  1. 同步锁
 Lock lock = new ReentrantLock();//(可以在类中直接 new) 
 lock.lock(); //中间的代码块进行加锁 lock.unlock();

56、Java中的锁有几种方式?

  1. Synchronized
  2. Lock

Synchronized的局限性:

  • a. 如果这个获取锁的线程由于要等待IO或者其他原因(比如调用sleep方法)被阻塞了,但是又没有释放锁,其他线程便只能等待。(不能主动释放锁)
  • b.当有多个线程读写文件时,读操作和写操作会发生冲突现象,写操作和写操作会发生冲突现象,但是读操作和读操作不会发生冲突现象如果多个线程都只是进行读操作,所以当一个线程在进行读操作时,其他线程只能等待无法进行读操作。(不分情况,一律锁死)

57、Lock的几个实现类?

  • ReentrantLock是一个可重入的互斥锁,又被称为“独占锁”。
  • ReadWriteLock,顾名思义,是读写锁。它维护了一对相关的锁 ——“读取锁”和“写入锁”,一个用于读取操作,另一个用于写入操作。他的两个实现类读锁readerLock和写锁writerLock。

58、线程间通信的几种实现方式?

  1. 使用 volatile 关键字。基于 volatile 关键字来实现线程间相互通信是使用共享内存的思想,大致意思就是多个线程同时监听一个变量,当这个变量发生变化的时候 ,线程能够感知并执行相应的业务。这也是最简单的一种实现方式。

  2. 使用Object类的wait() 和 notify() 方法。Object类提供了线程间通信的方法:wait()、notify()、notifyaAl(),它们是多线程通信的基础,而这种实现方式的思想自然是线程间通信。

注意: wait和 notify必须配合synchronized使用,wait方法释放锁,notify方法不释放锁

59、synchronized 和 Lock 的区别和应用场景?

  1. Lock 是接口,而 synchronized 是 Java 中的关键字,synchronized 是内置的语言实现;
  2. synchronized 在发生异常时,会自动释放线程占有的锁,因此不会导致死锁现象发生;而 Lock 在发生异常时,如果没有主动通过 unLock()去释放锁,则很可能造成死锁现象,因此使用 Lock 时需要在 finally 块中释放锁;
  3. Lock 可以让等待锁的线程响应中断,而 synchronized 却不行,使用synchronized 时,等待的线程会一直等待下去,不能够响应中断;
  4. 通过 Lock 可以知道有没有成功获取锁,而 synchronized 却无法办到。
  5. Lock 可以提高多个线程进行读操作的效率。
  6. Lock 能完成 Synchronized 所实现的所有功能在性能上来说,如果竞争资源不激烈,Synchronized 要优于 Lock,而当竞争资源非常激烈时(即有大量线程同时竞争),此时 Lock 的性能要远远优于synchronized。所以说,在具体使用时要根据适当情况选择。

60、为什么要用线程池?

创建线程要花费昂贵的资源和时间,如果任务来了才创建线程那么响应时间会变长,而且一个进程能创建的线程数 有限。为了避免这些问题,在程序启动的时候就创建若干线程来响应处理,它们被称为线程池,里面的线程叫工作线程。

从JDK1.5 开始,JavaAPI 提供了 Executor 框架让你可以创建不同的线程池。比如单线程池,每次处理一个 任务;数目固定的线程池或者是缓存线程池。

61、如何创建线程池?

  1. 线程池都是通过线程池工厂创建,再调用线程池中的方法获取线程,再通过线程去执行任务方法。
    Executors:线程池创建工厂类
  2. 自己根据创建线程池的需求来 new 对象(使用)
    注意:线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
    说明:Executors 返回的线程池对象的弊端如下:
    1)FixedThreadPool 和 SingleThreadPool:允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。
    2)CachedThreadPool 和 ScheduledThreadPool:允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。

建议自己通过 new 关键字创建 newThreadPoolExecutor

62、Java中的异常体系?

63、throw 和 throws 的区别?

  1. throws 用在函数上,后面跟的是异常类,可以跟多个;而 throw 用在函数内,后面跟的 是异常对象。
  2. throws is used to declare exceptions, so that the caller only knows the possible problems of this function, and can give a pre-processing method; throw throws a specific problem object, and when the execution reaches throw, the function is over and jumps to the caller. And throw the specific problem object to the caller. That is to say, when the throw statement exists independently, do not define other statements below, because it cannot be executed.
  3. Throws represents a possibility of exceptions, and these exceptions do not necessarily occur; throw means that an exception is thrown, and executing throw must throw some kind of exception object.
  4. Both are passive ways to handle exceptions, just throw or may throw exceptions, but the exceptions will not be handled by the function, and the real exception handling will be handled by the upper layer call of the function.

64. Name 5 common abnormalities?

  1. NullpointException: null pointer exception caused by null value
  2. IOExceptionIO abnormal IO stream common compilation exception
  3. SQLException SQL spelling exception, sql spelling exception in mybatis
  4. ClassNotFoundException Class not found exception is generally caused by jar package import failure or forgetting to write spring annotation
  5. ClassCastException type conversion exception

Guess you like

Origin blog.csdn.net/qq_40625778/article/details/122971370