首页  >  文章  >  Java  >  Java 多线程面试题

Java 多线程面试题

WBOY
WBOY原创
2024-08-30 16:29:25851浏览

在Java中,多线程涉及同时执行两个或多个线程,根据系统容量提高处理速度。多线程同时处理最小的单元,从而促进更快的执行。开发人员将其用于动画、游戏和管理大型应用程序等任务,有助于提高内存空间和时间效率。

现在,如果您正在寻找与 Java 多线程相关的工作,您需要准备 Java 多线程面试问题。根据职位简介,每次面试确实有所不同。在这里,我们准备了重要的 Java 多线程面试问题及其答案,这将帮助您在面试中取得成功。

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

本文将介绍有关 Java 多线程面试问题的 40 个最重要和最常见的问题。

Q1。解释一下Thread的不同状态。

答案:
线程的状态也称为线程的生命周期。以下是 Thread 的不同状态:

    • New:表示线程处于新建状态,需要在调用start方法之前创建线程类的实例。
    • Runnable:调用start方法后,线程处于可运行状态,调度器尚未选择其为运行线程。
    • 运行中:当选择线程调度器时,它处于运行状态。
    • 阻塞:也称为不可运行。当线程没有资格运行时,它仍然存活。
    • Termied:这是退出run方法或者处于dead状态时的状态。

Q2。 Java中的线程是什么?

答案:线程是指执行时间较短的小单元。它主要与执行路径无关。这是利用机器中可用的多个 CPU 的方法之一。在多线程的帮助下,CPU任务的处理变得更快。 Java主要用于提供对多线程的支持。 Java 支持多线程以利用多个处理器并提高程序性能。扩展 Thread 类或实现 Runnable 接口是创建线程的两种方法。

Q3。解释一下JAVA中线程和进程的区别。

答案:线程是进程内执行的最小任务。进程是一种独立的执行环境,具有多个线程或多个线程。线程是进程的细分。线程可以直接访问进程的数据段,而进程则拥有自己的数据段副本。线程主要共享进程创建的地址,进程有自己的地址。

线程可以轻松创建,进程创建需要做很多事情。线程可以很容易地与其他线程通信,而进程可以很容易地与子进程通信,但进程间通信很困难。线程有自己的堆栈,而进程共享堆内存等内存资源。如果线程中发生任何更改,都会影响所有线程,但在进程中,不会影响其他进程。

第四季度。解释一下Java内存模型。

答案:这些是面试中常见的 Java 多线程面试问题。在当前的 IT 行业中,多线程测试人员通常需要承担多项职责。

Java 内存模型建立了一组特定的规则,Java 程序必须遵守这些规则,以便在各种内存架构、CPU 和操作系统中表现出一致的行为。这些规则在多线程中起着至关重要的作用。Java 内存模型有助于区分在其中一个线程中所做的更改,并且该更改也应该对其他线程可见。这个 mod 是一个程序顺序,它表示每个线程的操作发生在程序顺序中较晚的每个线程之前。

Q5。讲解Java多线程中Volatile变量的使用。

答案:volatile 关键字或变量可确保每当多个线程进行更改时,共享变量或实例变量都会收到持续更新。它是一个特殊的修饰符,仅适用于实例变量,不适用于方法。在 Java 中将字段声明为 volatile 可确保 Java 内存模型保证该变量在所有线程中的值一致。程序总是从主存中读取易失性变量的值,从而减少内存一致性错误的可能性。此外,表示对象引用的 Java 易失性变量可以为 null。当一个变量在多个线程中使用时,需要使用 volatile 关键字。

Q6。解释线程中的竞争条件。

答案:当多个线程之间存在竞争时,就会出现竞争条件。这种竞争条件主要是由于一些编程错误或错误引起的。最初需要执行的线程在竞争中失败,然后执行第二个线程,并且代码行为发生一些变化,称为非确定性错误。由于线程的随机性,它成为难以发现和重现的错误之一。

Q7。解释一下Java中的fork-join框架。

答案:fork-join框架是在JDK7中引入的。它是 Java 开发人员利用当今世界服务器的多个处理器的强大工具。它主要是为可以分成较小部分的工作而设计的。主要目标是利用可用的处理能力来提高应用程序性能。它主要使用了工作窃取算法。

Q8。讲解Java中的线程池及其使用。

答案:线程池称为线程池。该线程通常称为工作线程。从许多方面来说,创建线程的成本很高,例如时间和资源。当您在请求进程时创建线程,通常会减慢处理器的响应时间,并且只能创建一些线程数量限制。所以,因为这两大问题,所以创建了线程池。在Java中,Java API允许我们创建不同类型的线程池,就像单个线程池一样,一次只需要一个进程。另一种是固定线程池,占用固定数量的线程。然后是一个缓存线程池,一个可扩展的线程池,主要适合很多任务。

Q9。线程之间如何共享数据?

答案:这些是面试中最流行的 Java 多线程面试问题。当前IT行业一些流行的测试用例。

借助共享对象或并发数据结构(如阻塞队列),可以在线程之间共享数据。它主要遵循生产者-消费者模式,使用等待并通知涉及在两个线程之间共享对象的方法。

问题10。线程在栈内存和堆内存中是如何分布的?

答案:在Java中,每个线程都有自己的堆栈,用于存储局部变量、方法参数和调用堆栈。堆内存是所有线程共享的公共内存。

Q11。区分线程和进程。

答案:

Feature Process Thread
Definition An autonomous program running. A process’s lightweight unit.
Execution Operates on its own. Operates within a process’s framework.
Communication Requires communication between processes. Communication made easier and data space shared.
Synchronization More remote and possibly requiring more overhead. Requires shared data synchronization mechanisms.
Resource Overhead Greater (differing memory spaces). Lower (shares the process’s resources).
Creation Time Slower and requiring more resources. Quicker and with less overhead needed.
Fault Tolerance More resilient. Failure could impact the entire process if it is not as strong.

Q12。 Java wait() 方法有什么用?

答案:Java使用notify()和notifyAll()方法配合wait()方法来实现同步和线程间通信。 Object 类是所有 Java 类的基础类,包含这些方法。语法如下:

public final void wait() throws InterruptedException

这意味着,如果你使用 wait(),你应该声明调用 wait() 的方法抛出此异常,或者捕获 InterruptedException。

Q13。用户线程和守护线程的区别?

答案:在 Java 中创建的线程称为用户线程。守护线程始终运行在后台,其完整的生命周期依赖于主线程。在后台运行的守护线程不会阻止 JVM 终止它。从守护线程创建的子线程也将是守护线程。

Q14。在 Java 中创建线程有哪些不同的方法?

答案:
Java中的线程可以通过两种方式创建:

  • 通过扩展 Thread 类
class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}

// Creating and starting the thread
MyThread myThread = new MyThread();
myThread.start();
  • 通过实现 Runnable 接口。
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}

// Creating a thread using the Runnable interface
Thread myThread = new Thread(new MyRunnable());
myThread.start();

Q15。 JAVA中Thread的生命周期是怎样的?

答:面试中有常见的Java面试问题,问到多线程。以下是线程的生命周期:

Java 多线程面试题

  • 可运行。
  • 跑步。
  • 已屏蔽。
  • 已终止。

Q16。如果我们调用 Thread 类的 run() 方法会发生什么?

答案:直接调用run()方法会成功编译并执行程序,但同一个程序不会被视为Thread,因为不会创建新的调用堆栈,程序会启动它的在主程序运行的同一调用堆栈中执行。

要创建一个应使用新调用堆栈运行的线程,必须使用 Thread 类的 start () 方法。

Q17。我们可以在特定时间暂停线程的执行吗?

答:是的,在Java中可以通过调用Thread类的sleep()来实现。 sleep() 方法还接受一个参数,该参数指示以毫秒为单位的时间。

Q18。 Java中如何实现线程的调度?

答案:是的,Java 中的线程调度是可能的。 Java中的线程调度有两种方式,即时间分片和抢占式调度。

让我们进入下一个关于多线程的 Java 面试问题。

Q19。一个线程可以启动两次吗?

答案:不,一个线程不能启动两次。如果我们尝试启动一个线程两次,它将抛出“java.lang.IllegalThreadStateException”。

Q20。 Java 中的关闭钩子是什么?

答案:这些是面试中最常见的关于多线程的 Java 面试问题。 shutdown hook 是一种用于在 JVM 正常或突然关闭时清理资源的机制。

Q21。什么是挥发性的?

答案:Volatile是java中的关键字,它可以与变量一起使用。如果一个变量被声明为 volatile,那么所有线程都会从主存而不是从缓存中读取同一个变量的值;因此,当多个线程在其操作中使用同一变量时,它可以防止错误读取。

Q22。 JAVA中如何实现线程?

答案:Java 提供了两种在程序中实现线程的方法。接口 java.Lang.Runnable 有一个 Java.lang.A 实例,需要通过实例执行任务的一行。 Thread 类已经实现了 Runnable,因此用户可以通过扩展 Thread 类或实现 Runnable 接口来直接重写 run() 方法。

Q23。 Java中什么时候使用Runnable,什么时候使用Thread?

答案:Java 提供了更好的实现 Runnable 接口而不是扩展 Thread 类,因为 Java 只允许单一继承。由于一个类可以实现多个接口,但只能扩展一个类,因此在类之间共享代码时,这提供了更大的灵活性。

Q24。 为什么说Thread的行为是不可预测的?

答案:原因是线程调度程序负责处理线程的执行。调度程序可以在 Windows、UNIX 和 LINUX 平台上执行不同的性能。执行时,同一个线程在不同平台上可能会给出不同的输出,有时甚至在同一平台上。为了解决这个问题,用户可以创建相同的 Runnable 对象,在两个线程中创建 run() 循环并同时启动这两行。

Q25. What is a volatile variable in Java, and what is its significance?

Answer: Java facilitates users to share variables present in different threads. A volatile variable acts as a unique modifier that can be used only for instance variables. It provides that a write will happen before any consequent read. The Java memory model ensures the consistency of this variable.

Q26. What is the use of the synchronized keyword? What is the difference between synchronized and volatile keywords?

Answer: The synchronized keyword is used when the goal is to allow only one thread to run at a time in a specific section of code. It can be applied to define four different types of blocks, as shown below:

  • Instance methods
  • Static methods
  • Code blocks inside instance methods
  • Code blocks inside static methods

It can be declared as follows:

Public synchronized void example () {}

A volatile variable will never land up in a deadlock as it does not require obtaining any lock. While in synchronized variables, it may end up in a draw if they are not done correctly.

Q27. Why methods like wait(), notify(), and notify all() are present in the object class and not in the Thread class?

Answer: Object class has monitors that allow the Thread to lock an object, while Thread does not have any monitors. The object class’s monitor checks for the thing to see if it is available. Thread class having these methods would not help as multiple threads exist on an object, not vice versa.

Q28. Explain the difference between sleep() and wait() methods.

Answer:

  • When the wait() method is called, the monitor moves the Thread from running to waiting for the state. Once a thread is in wait(), then it can move to runnable only when it has notified () or told all () for that object. The scheduler changes the state after this. While in the sleep() method, the state is changed to wait and will return to runnable only after sleep time.
  • The wait () method is a part of Java.lang.Object class, while sleep() is a part of Java.lang.Thread class.

Q29. How to force start a thread in Java?

Answer: In Java, multithreading, one cannot force start a thread. Only thread schedulers can control lines and are not exposed to any API for control.

Q30. Does Thread leave object lock when wait() and sleep() methods are called?

Answer: A thread in the sleep() method does not leave the lock and moves to the waiting state. The Thread waits for sleep time to get over.

Q31. Explain the advantages of Multithreading.

Answer :
When it comes to software development, multithreading has several benefits:

  1. Enhanced Performance: By utilizing multiple processor cores to execute tasks in parallel, multithreading improves the overall performance of applications.
  2. Responsiveness: Multithreading helps applications with graphical user interfaces stay responsive by running background tasks simultaneously.
  3. Resource Utilization: By allowing some threads to continue processing while others wait for I/O operations, efficient use of the system’s resources is achieved, maximizing the use of CPU and I/O devices.
  4. Maintainability and modularity: Multithreading encourages modular design by assigning distinct threads to handle different functions, which results in code that is easier to read and maintain.
  5. Asynchronous Programming: Multithreading makes it possible for tasks to run independently of the main program flow, which is essential for managing events or asynchronous input/output tasks.

Q32. How does time slicing differ from preemptive scheduling?

Answer:
1. Preemptive Scheduling: It is a scheduling technique used by operating systems that allows the system to start or stop a task that is presently underway in order to focus on a higher priority task.

Example: In a preemptive scheduling system, even if a lower-priority task is presently running, it may be preempted from execution if a higher-priority task becomes ready to run.

2. Round Robin Scheduling (Time Slicing): It is a scheduling technique where each process or thread is assigned a fixed time slot or quantum during which it can execute. Once the time slice expires, the next task in the queue is given CPU time.

For instance, if the time slice is set to 10 milliseconds and there are three tasks (A, B, and C), each task receives 10 milliseconds of CPU time in a cyclic fashion (A for 10 ms, then B for 10 ms, and so on).

Q33. What is deadlock?

Answer: Every thread in a system that is waiting for a resource that another waiting thread is holding causes a deadlock. In this case, all of the threads are in a universal waiting state because none of them can continue executing. A deadlock occurs when there is no opportunity for any thread to execute, leading to a halt. Complex circumstances known as deadlocks can impair a program’s regular runtime and possibly lead to coding problems. Maintaining the system’s performance and stability requires controlling and avoiding deadlocks.

Java 多线程面试题

Q34. How can a deadlock situation be identified? How is it easily avoidable?

Answer: Tools that display blocked threads, such as thread dumps, can be used to identify deadlocks. TryLock with timeouts, acquiring locks in a consistent order, and reducing lock contention are ways to prevent deadlocks. To lower the chance of deadlocks, properly design multithreaded programs and make use of higher-level concurrency tools.

Q35. Is there a stack for every thread in multithreaded programming?

Answer: Yes, every thread in multithreaded programming has a separate stack. Local variables and details about each thread’s function calls are kept on the stack. Each thread will function independently and have a dedicated area to manage its execution context because of this division.

Q36. How is a thread’s safety achieved?

Answer: A class is considered thread-safe when multiple threads can use its methods or objects concurrently without experiencing conflicts. In multithreaded programming, achieving thread safety is essential to avoiding race situations. This can be done in a few different ways:

  • Synchronization: Limiting access to shared resources by employing locks and other mechanisms to make sure that only one thread at a time can access crucial areas.
  • Volatile Keyword: Designating variables as volatile ensures consistency by making changes made to the variable by one thread visible to other threads.
  • Lock-Based Mechanism: This technique uses explicit locks, like ReentrantLock, to control access to important code segments and stop thread interference.
  • Atomic wrapper classes: (such as AtomicInteger and AtomicBoolean) for operations that must be carried out atomically without the need for explicit.

Q37. Tell me the difference between User thread and Daemon thread?

Answer: 

Characteristic User Threads

Daemon Threads

Creation and Control created and managed by the user or the application. The application or user creates and controls these threads, but they can be explicitly set as daemon threads using the setDaemon(true) method.
JVM Termination Impact JVM will wait for user threads to complete before exiting. JVM can exit even if daemon threads are still running. Daemon threads are abruptly stopped if all user threads have finished their execution.
Example (Java)
java Thread userThread 
= new Thread(() -> {
/* Thread logic */ 
}); 
userThread.start();
java Thread daemonThread = 
new Thread(() -> { 
/* Thread logic */ 
}); 
daemonThread.setDaemon(true);
daemonThread.start();

Q38. How are daemon threads made?

Answer: The Thread class in Java provides the setDaemon(boolean on) method, which can be used to create daemon threads. When all non-daemon threads have finished running, a daemon thread operates in the background and does not stop the Java Virtual Machine (JVM) from shutting down.

Here’s an easy illustration:

public class DaemonThreadExample {
public static void main(String[] args) {
Thread daemonThread = new Thread(() -> {
while (true) {
// Do some background tasks
System.out.println("Daemon Thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Setting the thread as daemon
daemonThread.setDaemon(true);
// Starting the daemon thread
daemonThread.start();
// Main thread
System.out.println("Main thread is finished");
}
}

Output:
Java 多线程面试题

Explanation:

The daemonThread.setDaemon(true) line in this example designates the thread as a daemon thread. Regardless of its state, the daemon thread will end when the main thread completes its execution and the JVM terminates.

It is crucial to remember that a thread will throw an IllegalThreadStateException if it is not started as a daemon. You are unable to alter a thread’s daemon status once it has begun.

Q39. How do notify() and notifyAll() differ from one another?

Answer:
1. notify():

Java 多线程面试题

  • Wakes up one of the threads that are currently waiting on the object.
  • The scheduling policy of the JVM determines which thread will be notified, and this decision is not guaranteed.

2. notifyAll():

Java 多线程面试题

  • Wakes up all the threads that are currently waiting on the object.
  • Usually makes sure that every thread in line has an opportunity to obtain the lock and verify the altered state.

Q40. What does it mean to be in a deadlock and when can it happen?

Answer: Multiple processes create a deadlock in computing when they become stuck holding resources, waiting for another process to acquire that resource. This situation prevents any progress and results in mutual blocking between the processes.

When the following four requirements referred to as the Coffman conditions—are satisfied, a deadlock usually results:

  • Mutual Exclusion: One or more resources must be kept in a non-sharable mode, which limits the resource’s use to a single process at a time.
  • Hold and Wait: A process needs to be holding one resource at a time while it waits to obtain more resources that other processes are holding.
  • No Preemption: Resources must be released willingly from a process; they cannot be taken away by force.
  • Circular Wait: When two or more processes are in a circular chain, each process is waiting for a resource that the subsequent process in the chain is holding.

以上是Java 多线程面试题的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn