Java多线程面试题小结
1.线程状态
下面是JDK中定义的线程状态
public enum State { /** * Thread state for a thread which has not yet started. */ NEW, /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ RUNNABLE, /** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED, /** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }
把其中的Runnable状态时是否获取到cpu时间片,可为Runnable和Running讨论,就有下面一张图
2.创建线程
1.继承Thread类 2.实现Runnable接口 3.实现Callable接口(有返回值,可抛出异常) 4线程池executors
3.有关线程的几个方法
1.sleep 睡眠,不释放锁。睡眠完进入就绪状态,是Thread类的方法。
2.wait 进入等待队列,释放锁。等待其他线程唤醒。
3.notify 唤醒等待队列的某个线程,唤醒后进入就绪状态。和wait一样必须在synchronized代码块中使用,用于线程间通讯。
4.yield 让步,由运行状态立即进入就绪状态。
5.await和signal condition类的方法,对应wait和notify(Object类),一个condition相当于一个锁池。
4.手写死锁
public class DeadLock { public static void main(String[] args) { Thread thread = new DeadLockThread("Thread1"); Thread thread2 = new DeadLockThread("Thread2"); thread.start(); thread2.start(); } } class DeadLockThread extends Thread{ private static final Object A = new Object(); private static final Object B = new Object(); public DeadLockThread(String name){ setName(name); } @Override public void run() { if ("Thread1".equals(getName())){ synchronized (A){ try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread1StartAndGetLockA"); synchronized (B){ System.out.println("Thread1StartAndGetLockB"); } } } if ("Thread2".equals(getName())){ synchronized (B){ System.out.println("Thread2StartAndGetLockB"); synchronized (A){ System.out.println("Thread2StartAndGetLockA"); } } } } }
5.线程池
ThreadPoolExecutor几个参数
核心线程数,最大线程数,存活时间,单位,工作队列,线程工厂,拒绝策略。
执行顺序:用银行柜台理解,常驻柜台(核心线程数),常驻柜台加临时柜台(最大线程数),等待区(工作队列),先排常驻柜台和等待区,全都满了开临时柜台窗口。
下面三个类也是调用ThreadPoolExecutor的构造方法,对应核心线程数,最大线程数,存活时间。(如下图)newCacheThreadPool(0,Integer.MAX_VALUE,60s) newFixedThreadPool(n,n,0) ,newSingleThreadPool(1,1,0)
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
使用线程池的好处:1)降低资源消耗。通过重复利用已创建的线程,降低线程创建和销毁造成的消耗。
2)提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。
3)增加线程的可管理型。线程是稀缺资源,使用线程池可以进行统一分配,调优和监控。
关于线程池细节可以参考 标题:《https://joonwhee.blog.csdn.net/article/details/106609583》 作者:程序员囧辉 链接:https://joonwhee.blog.csdn.net/article/details/106609583
6.锁升级
CAS用户态,自旋占用CPU。重量级锁,内核态,不占CPU资源。(待消化)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~