在Java中,多线程涉及同时执行两个或多个线程,根据系统容量提高处理速度。多线程同时处理最小的单元,从而促进更快的执行。开发人员将其用于动画、游戏和管理大型应用程序等任务,有助于提高内存空间和时间效率。
现在,如果您正在寻找与 Java 多线程相关的工作,您需要准备 Java 多线程面试问题。根据职位简介,每次面试确实有所不同。在这里,我们准备了重要的 Java 多线程面试问题及其答案,这将帮助您在面试中取得成功。
开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
本文将介绍有关 Java 多线程面试问题的 40 个最重要和最常见的问题。
答案:
线程的状态也称为线程的生命周期。以下是 Thread 的不同状态:
答案:线程是指执行时间较短的小单元。它主要与执行路径无关。这是利用机器中可用的多个 CPU 的方法之一。在多线程的帮助下,CPU任务的处理变得更快。 Java主要用于提供对多线程的支持。 Java 支持多线程以利用多个处理器并提高程序性能。扩展 Thread 类或实现 Runnable 接口是创建线程的两种方法。
答案:线程是进程内执行的最小任务。进程是一种独立的执行环境,具有多个线程或多个线程。线程是进程的细分。线程可以直接访问进程的数据段,而进程则拥有自己的数据段副本。线程主要共享进程创建的地址,进程有自己的地址。
线程可以轻松创建,进程创建需要做很多事情。线程可以很容易地与其他线程通信,而进程可以很容易地与子进程通信,但进程间通信很困难。线程有自己的堆栈,而进程共享堆内存等内存资源。如果线程中发生任何更改,都会影响所有线程,但在进程中,不会影响其他进程。
答案:这些是面试中常见的 Java 多线程面试问题。在当前的 IT 行业中,多线程测试人员通常需要承担多项职责。
Java 内存模型建立了一组特定的规则,Java 程序必须遵守这些规则,以便在各种内存架构、CPU 和操作系统中表现出一致的行为。这些规则在多线程中起着至关重要的作用。Java 内存模型有助于区分在其中一个线程中所做的更改,并且该更改也应该对其他线程可见。这个 mod 是一个程序顺序,它表示每个线程的操作发生在程序顺序中较晚的每个线程之前。
答案:volatile 关键字或变量可确保每当多个线程进行更改时,共享变量或实例变量都会收到持续更新。它是一个特殊的修饰符,仅适用于实例变量,不适用于方法。在 Java 中将字段声明为 volatile 可确保 Java 内存模型保证该变量在所有线程中的值一致。程序总是从主存中读取易失性变量的值,从而减少内存一致性错误的可能性。此外,表示对象引用的 Java 易失性变量可以为 null。当一个变量在多个线程中使用时,需要使用 volatile 关键字。
答案:当多个线程之间存在竞争时,就会出现竞争条件。这种竞争条件主要是由于一些编程错误或错误引起的。最初需要执行的线程在竞争中失败,然后执行第二个线程,并且代码行为发生一些变化,称为非确定性错误。由于线程的随机性,它成为难以发现和重现的错误之一。
答案:fork-join框架是在JDK7中引入的。它是 Java 开发人员利用当今世界服务器的多个处理器的强大工具。它主要是为可以分成较小部分的工作而设计的。主要目标是利用可用的处理能力来提高应用程序性能。它主要使用了工作窃取算法。
答案:线程池称为线程池。该线程通常称为工作线程。从许多方面来说,创建线程的成本很高,例如时间和资源。当您在请求进程时创建线程,通常会减慢处理器的响应时间,并且只能创建一些线程数量限制。所以,因为这两大问题,所以创建了线程池。在Java中,Java API允许我们创建不同类型的线程池,就像单个线程池一样,一次只需要一个进程。另一种是固定线程池,占用固定数量的线程。然后是一个缓存线程池,一个可扩展的线程池,主要适合很多任务。
答案:这些是面试中最流行的 Java 多线程面试问题。当前IT行业一些流行的测试用例。
借助共享对象或并发数据结构(如阻塞队列),可以在线程之间共享数据。它主要遵循生产者-消费者模式,使用等待并通知涉及在两个线程之间共享对象的方法。
答案:在Java中,每个线程都有自己的堆栈,用于存储局部变量、方法参数和调用堆栈。堆内存是所有线程共享的公共内存。
答案:
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. |
答案:Java使用notify()和notifyAll()方法配合wait()方法来实现同步和线程间通信。 Object 类是所有 Java 类的基础类,包含这些方法。语法如下:
public final void wait() throws InterruptedException
这意味着,如果你使用 wait(),你应该声明调用 wait() 的方法抛出此异常,或者捕获 InterruptedException。
答案:在 Java 中创建的线程称为用户线程。守护线程始终运行在后台,其完整的生命周期依赖于主线程。在后台运行的守护线程不会阻止 JVM 终止它。从守护线程创建的子线程也将是守护线程。
答案:
Java中的线程可以通过两种方式创建:
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();
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();
答:面试中有常见的Java面试问题,问到多线程。以下是线程的生命周期:
答案:直接调用run()方法会成功编译并执行程序,但同一个程序不会被视为Thread,因为不会创建新的调用堆栈,程序会启动它的在主程序运行的同一调用堆栈中执行。
要创建一个应使用新调用堆栈运行的线程,必须使用 Thread 类的 start () 方法。
答:是的,在Java中可以通过调用Thread类的sleep()来实现。 sleep() 方法还接受一个参数,该参数指示以毫秒为单位的时间。
答案:是的,Java 中的线程调度是可能的。 Java中的线程调度有两种方式,即时间分片和抢占式调度。
让我们进入下一个关于多线程的 Java 面试问题。
答案:不,一个线程不能启动两次。如果我们尝试启动一个线程两次,它将抛出“java.lang.IllegalThreadStateException”。
答案:这些是面试中最常见的关于多线程的 Java 面试问题。 shutdown hook 是一种用于在 JVM 正常或突然关闭时清理资源的机制。
答案:Volatile是java中的关键字,它可以与变量一起使用。如果一个变量被声明为 volatile,那么所有线程都会从主存而不是从缓存中读取同一个变量的值;因此,当多个线程在其操作中使用同一变量时,它可以防止错误读取。
答案:Java 提供了两种在程序中实现线程的方法。接口 java.Lang.Runnable 有一个 Java.lang.A 实例,需要通过实例执行任务的一行。 Thread 类已经实现了 Runnable,因此用户可以通过扩展 Thread 类或实现 Runnable 接口来直接重写 run() 方法。
答案:Java 提供了更好的实现 Runnable 接口而不是扩展 Thread 类,因为 Java 只允许单一继承。由于一个类可以实现多个接口,但只能扩展一个类,因此在类之间共享代码时,这提供了更大的灵活性。
答案:原因是线程调度程序负责处理线程的执行。调度程序可以在 Windows、UNIX 和 LINUX 平台上执行不同的性能。执行时,同一个线程在不同平台上可能会给出不同的输出,有时甚至在同一平台上。为了解决这个问题,用户可以创建相同的 Runnable 对象,在两个线程中创建 run() 循环并同时启动这两行。
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.
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:
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.
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.
Answer:
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.
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.
Answer :
When it comes to software development, multithreading has several benefits:
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).
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.
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.
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.
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:
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(); |
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:
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.
Answer:
1. notify():
2. notifyAll():
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:
以上是Java 多线程面试题的详细内容。更多信息请关注PHP中文网其他相关文章!