Lang:简体中文

多线程java面试题

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

掌握多线程面试要点,轻松应对挑战

在java面试中,多线程相关的问题是经常被问到的重点内容。下面就为大家详细介绍一些常见的多线程java面试题。

线程的创建方式

在java里,创建线程主要有三种方式。第一种是继承thread类,示例代码如下:

class mythread extends thread { public void run() { system.out.println("this is a thread created by extending thread class."); }}public class main { public static void main(string[] args) { mythread thread = new mythread(); thread.start(); }}

第二种是实现runnable接口,示例如下:

class myrunnable implements runnable { public void run() { system.out.println("this is a thread created by implementing runnable interface."); }}public class main { public static void main(string[] args) { thread thread = new thread(new myrunnable()); thread.start(); }}

第三种是使用callable和futuretask,代码如下:

import java.util.concurrent.callable;import java.util.concurrent.futuretask;class mycallable implements callable { public integer call() { return 100; }}public class main { public static void main(string[] args) { mycallable callable = new mycallable(); futuretask futuretask = new futuretask<>(callable); thread thread = new thread(futuretask); thread.start(); }}

线程的生命周期

线程的生命周期包含新建、就绪、运行、阻塞和死亡这几个状态。当创建一个thread对象时,线程处于新建状态;调用start()方法后,线程进入就绪状态,等待cpu调度;获得cpu时间片后进入运行状态;如果遇到阻塞事件,如sleep()、wait()等,线程进入阻塞状态;当线程的run()方法执行完毕或者出现异常,线程就进入死亡状态。

线程同步的方法

为了保证线程安全,需要进行线程同步。常见的方法有使用synchronized关键字和lock接口。使用synchronized关键字有两种形式,一种是同步方法,示例如下:

public class syncexample { public synchronized void method() { // 同步代码 }}

另一种是同步代码块,示例:

public class syncexample { public void method() { synchronized (this) { // 同步代码 } }}

使用lock接口的示例:

import java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;public class lockexample { private lock lock = new reentrantlock(); public void method() { lock.lock(); try { // 同步代码 } finally { lock.unlock(); } }}

线程池的使用

线程池可以提高线程的复用性,减少线程创建和销毁的开销。java提供了executors类来创建不同类型的线程池,如newfixedthreadpool、newcachedthreadpool等。示例代码如下:

import java.util.concurrent.executorservice;import java.util.concurrent.executors;public class threadpoolexample { public static void main(string[] args) { executorservice executorservice = executors.newfixedthreadpool(5); for (int i = 0; i < 10; i++) { executorservice.execute(new runnable() { public void run() { system.out.println(thread.currentthread().getname()); } }); } executorservice.shutdown(); }}

死锁的概念和避免方法

死锁是指两个或多个线程在执行过程中,因争夺资源而造成的一种互相等待的现象。要避免死锁,可以采用资源一次性分配、按顺序获取资源等方法。例如,有两个线程t1和t2,t1持有资源a并请求资源b,t2持有资源b并请求资源a,就可能产生死锁。如果规定所有线程都先获取资源a再获取资源b,就可以避免死锁。

以下为推荐内容

微信二维码