java2023多线程面试题

这是一道频率出现比较高的面试题,像阿里、腾讯、京东的Java初中级工程师面试题都出现过、面试过了薪水也能拿个10K~20K,所以掌握这些基础的知识还是有必要的。

1、继承Thread类,重写run方法
启动线程使用的是start方法,这样会启动一个新的线程,并执行线程的任务。如果直接调用run方法,则可以执行run方法中的逻辑代码。

public class ThreadDemo {

    public static void main(String[] args) {
        MyJob job = new MyJob();
        job.start();
    }

    static class MyJob extends Thread{
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                System.out.println("数字:" + i);
            }
        }
    }
}

2、实现Runnable接口,重写run方法
此方法比继承Thread要灵活,因为类只能继承一个父类,而可以实现多个接口

public class RunnabeDemo {

    public static void main(String[] args) {
      new Thread(new MyRunnable()).start();
    }

    static class MyRunnable implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("runnale:" + i);
            }
        }
    }
}

3、实现Callabe,重写call方法,然后与FutureTask一起使用
callable一般用于有返回值非阻塞的方法中

public class CallableDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyCallable callable = new MyCallable();
        FutureTask<String> task = new FutureTask(callable);
        Thread thread = new Thread(task);
        thread.start();
        Object o = task.get();
        System.out.println(o);
    }

    static class MyCallable implements Callable<String>{

        @Override
        public String call() throws Exception {
            int count = 0;
            for (int i = 0; i < 10; i++) {
                System.out.println("MyCallable== " + i);
                count += i;
            }
            return count + "";
        }
    }
}

4、使用ExecutorService、Callable、Future实现有返回结果的线程:
ExecutorService、Callable、Future三个接口实际上都是属于Executor框架。返回结果的线程是在JDK1.5中引入的新特征,有了这种特征就不需要再为了得到返回值而大费周折了。而且自己实现了也可能漏洞百出。
可返回值的任务必须实现Callable接口。类似的,无返回值的任务必须实现Runnable接口。
执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。

注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。

public class ThreadPoolDemo {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    public void execute() throws InterruptedException, ExecutionException {

        CountDownLatch countDownLatch = new CountDownLatch(5);
        Future future = threadPoolExecutor.submit(() -> {
            System.out.println("hello");
        });
        Object o = future.get();
        countDownLatch.await();

    }

    @Slf4j
    public class QuartzRunnable implements Callable {

        private Object target;
        private Method method;
        private String params;

        @Override
        public Object call() throws Exception {
            ReflectionUtils.makeAccessible(method);
            if (StringUtils.isNotBlank(params)) {
                method.invoke(target, params);
            } else {
                method.invoke(target);
            }
            return null;
        }
    }

}

@Configuration
@EnableAsync
class ThreadPool {
    @Value("${threadPool.core-pool-size}")
    private int corePoolSize;

    @Value("${threadPool.max-pool-size}")
    private int maxPoolSize;

    @Value("${threadPool.keep-alive-time}")
    private int keepAliveTime;

    public ThreadPoolExecutor getExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.MICROSECONDS,
                new ArrayBlockingQueue<>(300)
        );
        return executor;
    }
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值