多线程面试常问

发布于:2024-08-25 ⋅ 阅读:(151) ⋅ 点赞:(0)

一、创建线程的几种方式

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

public class MyThread extends Thread {
	@Override
	public 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> {
	@Override
	public 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.ThreadPoolExecutor
		
		System.out.println(service.getClass());

		ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
		
		//自定义线程池的属性
		
		//        service1.setCorePoolSize(15);
		//        service1.setKeepAliveTime();
		//2. 执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
		service.execute(new NumberThread());//适用于Runnable
		service.execute(new NumberThread1());//适用于Runnable
		//        service.submit(Callable callable);//适合使用于Callable
		//3. 关闭连接池
		service.shutdown();
		}
		}

 

二、线程的几种状态

 

 

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

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

三、notify和notifyAll的区别

notify只是随机唤醒一个线程

notifyAll是唤醒所有的线程

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

五、锁升级过程

 


网站公告

今日签到

点亮在社区的每一天
去签到