您的位置:首页 > 房产 > 家装 > 多线程面试常问

多线程面试常问

2025/7/26 16:24:31 来源:https://blog.csdn.net/weixin_50737119/article/details/141499636  浏览:    关键词:多线程面试常问

一、创建线程的几种方式

1、继承Thread类并重写run()方法。

public class MyThread extends Thread {@Overridepublic void run() {System.out.println("通过集成 Thread 类实现线程");
}
}
// 如何使用
new MyThread().start()

2、实现Runnable接口并重写run()方法。将Runnable实例作为Thread类的构造函数参数传递并启动线程。

public class MyRunnable implements Runnable {
@Override
public void run() {System.out.println("通过实现 Runnable 方式实现线程");
}
}
// 使用
// 1、创建MyRunnable实例
MyRunnable runnable = new MyRunnable();
//2.创建Thread对象
//3.将MyRunnable放入Thread实例中
Thread thread = new Thread(runnable);
//4.通过线程对象操作线程(运行、停止)
thread.start();


3、实现Callable接口并重写call()方法。使用ExecutorService的submit()方法提交Callable任务,并通过Future对象获取返回值。

public class MyCallable implements Callable<Integer> {@Overridepublic Integer call() throws Exception {return new Random().nextInt();}
// 使用方法
// 1、创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
// 2、提交任务,并用 Future提交返回结果
Future<Integer> future = service.submit(new MyCallable());
}

4.使用线程池。线程池可以重复使用线程,提高性能和可靠性。Java提供了Executor框架来管理线程池。常见的线程池实现类包括ThreadPoolExecutor和ScheduledThreadPoolExecutor

public class ThreadPool {public static void main(String[] args) {//1. 提供指定线程数量的线程池ExecutorService service = Executors.newFixedThreadPool(1);//输出class java.util.concurrent.ThreadPoolExecutorSystem.out.println(service.getClass());ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;//自定义线程池的属性//        service1.setCorePoolSize(15);//        service1.setKeepAliveTime();//2. 执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象service.execute(new NumberThread());//适用于Runnableservice.execute(new NumberThread1());//适用于Runnable//        service.submit(Callable callable);//适合使用于Callable//3. 关闭连接池service.shutdown();}}

 

二、线程的几种状态

 

 

二、如何保证线程执行顺序

使用join,可以等待线程执行完成

三、notify和notifyAll的区别

notify只是随机唤醒一个线程

notifyAll是唤醒所有的线程

四、java中wait和sleep方法的不同

五、锁升级过程

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com