Lang:简体中文

start线程面试题

日期:2025-09-08 / 来源:面试宝典

深入剖析start线程面试要点

在面试过程中,start线程相关的问题是常见考点。了解这些问题,有助于我们在面试中脱颖而出。下面将详细介绍一些常见的start线程面试题。

start方法和run方法的区别

这是最基础也是最常考的问题。start方法用于启动一个新线程,它会调用线程的run方法,让线程进入就绪状态,等待cpu调度。而run方法只是一个普通的方法调用,不会启动新线程。例如,以下代码展示了两者的区别:

java

public class threadexample {

public static void main(string[] args) {

thread thread = new thread(() -> {

system.out.println("running in a new thread."); });

// 调用run方法

thread.run(); // 直接在主线程中执行

// 调用start方法

thread.start(); // 启动新线程执行

}

}

在上述代码中,调用run方法时,代码在主线程中执行;而调用start方法时,会启动一个新线程来执行代码。

多次调用start方法会怎样

如果多次调用start方法,会抛出illegalthreadstateexception异常。因为一个线程只能启动一次,当线程启动后,它的状态会从new变为其他状态,再次调用start方法就会违反线程的生命周期规则。例如:

java

public class multiplestartexample {

public static void main(string[] args) {

thread thread = new thread(() -> {

system.out.println("thread is running."); });

thread.start(); // 第一次启动

try {

thread.start(); // 再次启动,会抛出异常

} catch (illegalthreadstateexception e) {

system.out.println("exception: " + e.getmessage());

}

}

}

运行这段代码,第二次调用start方法时就会抛出异常。

start方法是如何启动线程的

start方法内部会调用本地方法start0,这是一个由jvm实现的方法,它会创建一个新的操作系统线程,并将java线程和操作系统线程进行关联。当操作系统调度这个新线程时,就会调用java线程的run方法。简单来说,start方法通过jvm和操作系统的协作来启动一个新线程。

start方法和线程池的关系

线程池是一种管理线程的机制,它可以复用线程,减少线程创建和销毁的开销。在使用线程池时,通常不会直接调用线程的start方法,而是将任务提交给线程池,线程池会管理线程的启动和执行。例如:

java

import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

public class threadpoolexample {

public static void main(string[] args) {

executorservice executorservice = executors.newfixedthreadpool(2);

executorservice.submit(() -> {

system.out.println("task is running in thread pool."); });

executorservice.shutdown();

}

}

在这个例子中,我们使用线程池来执行任务,而不是直接调用线程的start方法。

如何确保线程启动后再执行后续操作

可以使用join方法来确保线程启动并执行完毕后再执行后续操作。join方法会阻塞当前线程,直到调用join方法的线程执行完毕。例如:

java

public class joinexample {

public static void main(string[] args) throws interruptedexception {

thread thread = new thread(() -> {

try {

thread.sleep(2000);

} catch (interruptedexception e) {

e.printstacktrace();

}

system.out.println("thread is finished."); });

thread.start();

thread.join();

system.out.println("main thread continues.");

}

}

在这个例子中,主线程会等待子线程执行完毕后再继续执行。

以下为推荐内容

微信二维码