阿里二面必备考题之Java并发!全面解析

一、使用线程

有三种使用线程的方法:

  • 实现Runnable接口
  • 实现Callable接口
  • 继承Thread类

实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以理解为任务是通过线程驱动从而执行的。【获取资源】

实现Runnable接口

1public class MyRunnable implements Runnable { 2 @Override 3 public void run() { 4 // ... 5 } 6}

使用Runnable实例再创建一个Thread实例,然后调用Thread实例的start方法来启动线程。

1public static void main(String[] args) { 2 MyRunnable instance = new MyRunnable(); 3 Thread thread = new Thread(instance); 4 thread.start(); 5}

实现Callable接口

与Runnable相比,Callable可以有返回值,返回值通过FutureTask进行封装【获取资源】

1public class MyCallable implements Callable<Integer> { 2 public Integer call() { 3 return 123; 4 } 5}
1public static void main(String[] args) throws ExecutionException, InterruptedException { 2 MyCallable mc = new MyCallable(); 3 FutureTask<Integer> ft = new FutureTask<>(mc); 4 Thread thread = new Thread(ft); 5 thread.start(); 6 System.out.println(ft.get()); 7}

继承 Thread 类

同样是需要实现run()方法,因为Thread类也实现了Runable接口。【获取资源】

当调用start()方法启动一个线程时,虚拟机会将该线程放入就绪队列中等待被调度,当一个线程被调度时会执行该线程的run方法。【获取资源】

1public class MyThread extends Thread { 2 public void run() { 3 // ... 4 } 5}
1public static void main(String[] args) { 2 MyThread mt = new MyThread(); 3 mt.start(); 4}

实现接口VS继承Thread

实现接口会更好一些,因为:

  • java不支持多重继承,因此继承了Thread类就无法继承其他类,但是可以实现多个接口
  • 类可能只要求可执行就行,继承整个Thread类开销过大。【获取资源】

二、基础线程机制

线程池有什么作用?

线程池作用就是限制系统中执行线程的数量。【获取资源】

1、提高效率 创建好一定数量的线程放在池中,等需要使用的时候就从池中拿一个,这要比需要的时候创建一个线程对象要快的多。【获取资源】

2、方便管理 可以编写线程池管理代码对池中的线程统一进行管理,比如说启动时有该程序创建100个线程,每当有请求的时候,就分配一个线程去工作,如果刚好并发有101个请求,那多出的这一个请求可以排队等候,避免因无休止的创建线程导致系统崩溃。【获取资源】

Executor

Executor管理多个异步任务的执行,而无需程序员显式地管理线程的生命周期。这里的异步是指多个任务的执行互不干扰,不需要进行同步操作。【获取资源】

主要有三种Executor:

  • CachedThreadPool:一个任务创建一个线程,无限扩大,适合轻负载。
  • FixedThreadPool:所有任务只能使用固定大小的线程,固定线程池,适合重负载。
  • SingleThreadExecutor:相当于大小为1的FixedThreadPool.创建单线程的线程池,适用于需要保证顺序执行各个任务。
1public static void main(String[] args) { 2 ExecutorService executorService = Executors.newCachedThreadPool(); 3 for (int i = 0; i < 5; i++) { 4 executorService.execute(new MyRunnable()); 5 } 6 executorService.shutdown(); 7}

Daemon

守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分。

当所有非守护线程结束时,程序也就终止,同时会杀死所有守护线程。

mian()属于非守护线程。

在线程启动之前使用setDaemon()方法可以将一个线程设置为守护线程。

1public static void main(String[] args) { 2 Thread thread = new Thread(new MyRunnable()); 3 thread.setDaemon(true); 4}

sleep()

Thread.sleep(millisec)方法会休眠当前正在执行的线程,millisec单位为毫秒。

sleep()可能会抛出InterruptedExecption,因为异常不能跨线程传播回main()中,因此必须在本地处理。线程中抛出的其他异常也同样需要在本地进行处理。【获取资源】

1public void run() { 2 try { 3 Thread.sleep(3000); 4 } catch (InterruptedException e) { 5 e.printStackTrace(); 6 } 7}

三、中断

一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。【获取资源】

InterruptedExecption

通过调用一个线程的interrupt()来中断该线程,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出InterruptedException,从而提前结束该线程。但是不能中断I/O阻塞和suynchronized锁阻塞。【获取资源】

对于以下代码,在main()中启动一个线程之后再中断它,由于线程中调用了Thread.sleep()方法, 因此会抛出一个 InterruptedException,从而提前结束线程,不执行之后的语句。

1public class InterruptExample { 2 3 private static class MyThread1 extends Thread { 4 @Override 5 public void run() { 6 try { 7 Thread.sleep(2000); 8 System.out.println("Thread run"); 9 } catch (InterruptedException e) { 10 e.printStackTrace(); 11 } 12 } 13 } 14}
1public static void main(String[] args) throws InterruptedException { 2 Thread thread1 = new MyThread1(); 3 thread1.start(); 4 thread1.interrupt(); 5 System.out.println("Main run"); 6}
1Main run 2java.lang.InterruptedException: sleep interrupted 3 at java.lang.Thread.sleep(Native Method) 4 at InterruptExample.lambda$main$0(InterruptExample.java:5) 5 at InterruptExample$$Lambda$1/713338599.run(Unknown Source) 6 at java.lang.Thread.run(Thread.java:745)

Executor 的中断操作

调用Executor的shutdown()方法会等待线程都执行完毕之后再关闭,但是如果调用的是shutdownNow()方法,则相当于调用每个线程的interrupt()方法。【获取资源】

以下使用Lambda创建线程,相当于创建了一个匿名内部线程。

1public static void main(String[] args) { 2 ExecutorService executorService = Executors.newCachedThreadPool(); 3 executorService.execute(() -> { 4 try { 5 Thread.sleep(2000); 6 System.out.println("Thread run"); 7 } catch (InterruptedException e) { 8 e.printStackTrace(); 9 } 10 }); 11 executorService.shutdownNow(); 12 System.out.println("Main run"); 13}
1Main run 2java.lang.InterruptedException: sleep interrupted 3 at java.lang.Thread.sleep(Native Method) 4 at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9) 5 at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source) 6 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 7 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 8 at java.lang.Thread.run(Thread.java:745) 9 ``` 10如果只想中断 Executor 中的一个线程,可以通过使用 submit() 方法来提交一个线程,它会返回一个 Future<?> 对象,通过调用该对象的 cancel(true) 方法就可以中断线程。 11```c 12Future<?> future = executorService.submit(() -> { 13 // .. 14}); 15future.cancel(true);

四、互斥同步

java提供了两种锁机制来控制多个线程对共享资源的互斥访问,第一个是JVM实现的synchronized,而另一个是JDK实现的ReentrantLock。【获取资源】

synchronized

1、同步一个代码块

1public void func() { 2 synchronized (this) { 3 // ... 4 } 5}

它只作用于同一个对象,如果调用两个对象上的同步代码块,就不会进行同步。

对于以下代码,使用 ExecutorService 执行了两个线程,由于调用的是同一个对象的同步代码块,因此这两个线程会进行同步,当一个线程进入同步语句块时,另一个线程就必须等待。

1public class SynchronizedExample { 2 3 public void func1() { 4 synchronized (this) { 5 for (int i = 0; i < 10; i++) { 6 System.out.print(i + " "); 7 } 8 } 9 } 10}
1public static void main(String[] args) { 2 SynchronizedExample e1 = new SynchronizedExample(); 3 ExecutorService executorService = Executors.newCachedThreadPool(); 4 executorService.execute(() -> e1.func1()); 5 executorService.execute(() -> e1.func1()); 6}
10 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

对于一下代码,两个线程调用了不同对象的同步代码块,因此这两个线程就不需要同步。从输出结果看出,两个线程交叉执行。

1public static void main(String[] args) { 2 SynchronizedExample e1 = new SynchronizedExample(); 3 SynchronizedExample e2 = new SynchronizedExample(); 4 ExecutorService executorService = Executors.newCachedThreadPool(); 5 executorService.execute(() -> e1.func1()); 6 executorService.execute(() -> e2.func1()); 7}
10 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

2、同步一个方法

1public synchronized void func () { 2 // ... 3}

它和同步代码块一样,作用于同一个对象

3、同步一个类

1public void func() { 2 synchronized (SynchronizedExample.class) { 3 // ... 4 } 5}

作用于整个类,也就是说两个线程调用同一个类的不同对象上的这种同步语句,也会进行同步。

1public class SynchronizedExample { 2 3 public void func2() { 4 synchronized (SynchronizedExample.class) { 5 for (int i = 0; i < 10; i++) { 6 System.out.print(i + " "); 7 } 8 } 9 } 10}
1public static void main(String[] args) { 2 SynchronizedExample e1 = new SynchronizedExample(); 3 SynchronizedExample e2 = new SynchronizedExample(); 4 ExecutorService executorService = Executors.newCachedThreadPool(); 5 executorService.execute(() -> e1.func2()); 6 executorService.execute(() -> e2.func2()); 7}
10 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

4、同步一个静态方法

1public synchronized static void fun() { 2 // ... 3}

作用于整个类。

ReentrantLock

ReentrantLock是java.util.concurrent(J.U.C)包中的锁。

1public class LockExample { 2 3 private Lock lock = new ReentrantLock(); 4 5 public void func() { 6 lock.lock(); 7 try { 8 for (int i = 0; i < 10; i++) { 9 System.out.print(i + " "); 10 } 11 } finally { 12 lock.unlock(); // 确保释放锁,从而避免发生死锁。 13 } 14 } 15}
1public static void main(String[] args) { 2 LockExample lockExample = new LockExample(); 3 ExecutorService executorService = Executors.newCachedThreadPool(); 4 executorService.execute(() -> lockExample.func()); 5 executorService.execute(() -> lockExample.func()); 6}
10 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

比较

1、锁的实现

synchronized是JVM实现的,而ReentrantLock是JDK实现的。

2、性能

新版本java对synchronized进行了很多优化,例如自旋锁等,synchronized与ReentrantLock大致相同。

3、等待可中断

当持有锁的线程长期不释放锁的时候,正在等待的线程可以选择放弃等待,改为处理其他事情。

ReentrantLock 可中断,而 synchronized 不行。

4、公平锁【获取资源】

公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁。

synchronized 中的锁是非公平的,ReentrantLock 默认情况下也是非公平的,但是也可以是公平的。

5、锁绑定多个条件

一个 ReentrantLock 可以同时绑定多个 Condition 对象。【获取资源】

使用选择

除非使用ReentrantLock的高级功能,否则优先使用synchronized。这是因为synchronized是JVM实现的一种锁机制,JVM原生地支持,而ReentrantLock不是所有的JDK版本都支持。并且使用synchronized不用担心没有释放锁而导致死锁问题,因为JVM会确保锁的释放。【获取资源】

最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。

本次给大家推荐一个免费的学习君样:894102285里面概括很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解及面试资源等。 对Java开发技术感兴趣的同学,欢迎加入Q君样:894102285,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。 最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。 在这里插入图片描述

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java多线程实现的三种方式

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。1、继承Thread类实现多线程继承Thread类的方法尽管被我列为一种多线程实现方式,但Thread本质上也是实现

一篇文章弄懂Java多线程基础和Java内存模型

文章目录一、多线程的生命周期及五种基本状态二、Java多线程的创建及启动1.继承Thread类,重写该类的run()方法2.通过实现Runnable接口创建线程类3.通过Callable和Future接口创建线程三、Java内存模型概念四、内存间的交互操作五、volatile和synchronized的

Executor线程池

线程池为线程生命周期的开销和资源不足问题提供了解决方案。通过对多个任务重用线程,线程创建的开销被分摊到了多个任务上。_0_|_1_线程实现方式Thread、Runnable、Callable//实现Runnable接口的类将被Thread执行,表示一个基本任务p