Moosphan / Android-Daily-Interview

:pushpin:每工作日更新一道 Android 面试题,小聚成河,大聚成江,共勉之~

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

2019-05-30:Java 中使用多线程的方式有哪些?

Moosphan opened this issue · comments

2019-05-30:Java 中使用多线程的方式有哪些?
commented

大概这么4种(如果有其他的方式,麻烦告诉我,奖励你们小花花~):
extends Thread ;
impl Runnable;
impl Callable 通过 FutureTask 包装器来创建线程;
使用ExecutorService、Callable、Future实现有返回结果的多线程。;
extends Thread 和 impl Runnable 的线程没有返回值, 而 FutureTask 和 ExecutorService(ExecutorService.submit(xxx) return Future<?> ) 有返回值.

感觉回答的不太准确


1、继承Thread类创建线程
Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。
2、实现Runnable接口创建线程
如果自己的类已经extends另一个类,就无法直接extends Thread,此时,可以实现一个Runnable接口
3、实现Callable接口通过FutureTask包装器来创建Thread线程
Callable接口(也只有一个方法
4、4、使用ExecutorService、Callable、Future实现有返回结果的线程

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

常用的方式:

1,继承 Thread

2,实现Runnable 接口

3,通过线程池池 创建线程

private static final ThreadFactory FACTORY = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger();
@OverRide
public Thread newThread(Runnable r) {
return new Thread(r,"text ---- #"+mCount.getAndIncrement());
}
};
public static void main(String[] args) {
ThreadPoolExecutor textPool = new ThreadPoolExecutor(3,
5, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque(),FACTORY);
for (int i = 0; i < 10; i++) {
textPool.execute(new Runnable() {
@OverRide
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
}

结果
text ---- #1
text ---- #2
text ---- #0
text ---- #2
text ---- #1
text ---- #2
text ---- #0
text ---- #2
text ---- #1
text ---- #0

常见的
1.继承Thread类
2.实现Runnable接口
3.通过线程池创建

  1. Thread 和 Runnable
  • Thread
    Thread thread = new Thread() { @Override public void run() { System.out.println("Thread started!"); } }; thread.start();

  • Runnable

Runnable runnable = new Runnable() { @Override
public void run() { System.out.println("Thread with
Runnable started!");
    }
};
Thread thread = new Thread(runnable); thread.start();```
    1. 继承Thread类,从写run方法
    1. 实现Runnable接口,传递给Thread(runnable)构造函数。
    1. 通过ExecutorService 线程池进行创建多线程
    1. 通过FutureTask + Executors 实现带有返回值的多线程
  • 继承Thread类,重写run() 方法。
  • 实现Runnable接口, 通过Thread构造函数Thread(Runnable runnable).
  • 通过ExecutorService线程池进行多线程的创建
    • newThreadPoolExecutor() 基本的线程池
    • newFixedThreadPool() 可重用固定线程数
    • newCacheThreadPool() 缓存线程池,按需创建
    • newSingleThreadPool() 单核心线程池
    • newScheduledThreadPool() 延时线程池

1、继承Thread类来实现

2、重写Runnable接口

3、重写Callable接口

4、通过线程池启动