大家好,我是walker
一个从文科自学转行的程序员~
爱好编程,偶尔写写编程文章和生活
欢迎关注公众号【I am Walker】,回复“电子书”,就可以获得200多本编程相关电子书哈~
我的gitee:https://gitee.com/shen-chuhao/walker.git 里面很多技术案例!
方式一:继承Thread
package createThread.thread;
//1、集成Thread类
public class MyThread extends Thread{
//2、重写run方法
@Override
public void run() {
//Thread.currentThread().getName() 这里打印的结果是当前线程的名称
System.out.println(Thread.currentThread().getName()+"线程正在执行中");
}
}
package createThread.thread;
public class ThreadTest {
public static void main(String[] args) {
MyThread myThread = new MyThread();
//3、使用start方法,而不是使用run()
myThread.start();
}
}
//输出结果:
Thread-0线程正在执行中
注意:
- 这里使用run()和start()方法是有区别的,如果使用run()方法,则是执行一次普通类的方法而已,但是使用start方法,则是调用的线程的启动方法。
方式二:实现Runnable接口
package createThread.runnable;
//1、实现Runnbale接口
public class MyRunnbale implements Runnable{
//2、重写run方法
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"使用runnable方式执行线程");
}
}
package createThread.runnable;
public class RunnableTest {
public static void main(String[] args) {
//3、创建MyRunnbale对象
MyRunnbale myRunnbale = new MyRunnbale();
//4、构造Thread对象,myRunnable作为参数
Thread thread = new Thread(myRunnbale);
//5、执行thread方法
thread.start();
}
}
//执行结果
Thread-0使用runnable方式执行线程
总结:
- 使用runnable接口的实现方式与继承Thread的有些区别,主要是使用的构造方法的不同,使用的是该构造方法
Thread(Runnable target)
,然后构造出thread对象之后,再使用thread的start方法执行
方式三:实现Callable
package createThread.callable;
import java.util.concurrent.Callable;
//1、实现Callable接口,可以在类的泛型中接一个对象类型,可用于call()方法的返回结果,如果不定义的话,call()的返回结果是Object对象
public class MyCallable implements Callable<Integer> {
//2、重写call方法,区别于run()方法,call()是可以返回结果的
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+"正在使用callable执行线程");
return 1;
}
}
package createThread.callable;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) {
//3、创建MyCallable对象
MyCallable myCallable = new MyCallable();
//4、创建FutureTask对象
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
//5、创建Thread对象,将futureTask对象放入参数
Thread thread = new Thread(futureTask);
//6、使用start方法启动线程
thread.start();
//7、测试callable返回结果,这里的返回结果,只有call方法执行完成才能够返回,有点类似于异步
Integer res = futureTask.get();
System.out.println("callable线程返回结果:"+res);
}
}
//返回结果
总结:
- 相对于Thread和Runnbale实现方式而言,Callable在启动的时候比较麻烦,需要先创建一个FutureTask对象
FutureTask
参考:https://blog.youkuaiyun.com/qq_39654841/article/details/90631795
一个可取消的异步计算。
FutureTask提供了对Future的基本实现,可以调用方法去开始和取消一个计算,可以查询计算是否完成并且获取计算结果。
只有当计算完成时才能获取到计算结果,一旦计算完成,计算将不能被重启或者被取消,除非调用runAndReset方法。
除了实现了Future接口以外,FutureTask还实现了Runnable接口,因此FutureTask交由Executor执行,也可以直接用线程调用执行(futureTask.run())。
根据FutureTask的run方法执行的时机,FutureTask可以处于以下三种执行状态:
1、未启动:在FutureTask.run()还没执行之前,FutureTask处于未启动状态。当创建一个FutureTask对象,并且run()方法未执行之前,FutureTask处于未启动状态。
2、已启动:FutureTask对象的run方法启动并执行的过程中,FutureTask处于已启动状态。
3、已完成:FutureTask正常执行结束,或者FutureTask执行被取消(FutureTask对象cancel方法),或者FutureTask对象run方法执行抛出异常而导致中断而结束,FutureTask都处于已完成状态。
方式四: Executors
Executors提供了一系列工厂方法用于创先线程池
主要有newFixedThreadPool,newCachedThreadPool,newSingleThreadExecutor,newScheduledThreadPool。
Executors主要方法的区别
主要有以下的区别:
(1)newSingleThreadExecutor:
- 创建一个单线程的线程池。
- 这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。
- 如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。
- 此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
(2)newFixedThreadPool:
- 创建固定大小的线程池。
- 每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。
- 线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。
- 如果希望在服务器上使用线程池,建议使用 newFixedThreadPool方法来创建线程池,这样能获得更好的性能。
(3) newCachedThreadPool:
- 创建一个可缓存的线程池。
- 如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60 秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。
- 此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说 JVM)能够创建的最大线程大小。
(4)newScheduledThreadPool:
- 创建一个大小无限的线程池。
- 此线程池支持定时以及周期性执行任务的需求。
但是《阿里巴巴Java开发手册》中强制线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险
使用案例
创建一个Executor,该Executor使用单个工作线程在无界队列上操作。 (但是请注意,如果这个单线程在关闭之前由于执行失败而终止,如果需要执行后续任务,一个新的线程将取代它。) 任务保证按顺序执行,并且在任何给定时间活动的任务不超过一个。 与其他等效的newFixedThreadPool(1)不同,返回的执行器保证不会被重新配置以使用其他线程。
返回:
新创建的单线程Executor
package createThread.executors;
//1、使用实现Runnbale的方式构建一个线程类,这里的实现方式不细讲,参考Runnable的实现方式
public class MyExecutorRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行方法");
}
}
package createThread.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleExecutorTest {
public static void main(String[] args) {
//2、创建线程对象
MyExecutorRunnable myExecutorRunnable = new MyExecutorRunnable();
//3、使用Executors.newSingleThreadExecutor()创建一个执行器
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
//4、执行创建的实现Runnbale接口的线程对象,就会去执行线程的方法了
executor.execute(myExecutorRunnable);
}
//5、最后将执行器进行关闭
executor.shutdown();
}
}
方式五: ThreadPoolExecutor
Executors 各个方法的弊端:
- newFixedThreadPool 和 newSingleThreadExecutor:主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至 OOM。
- newCachedThreadPool 和 newScheduledThreadPool:主要问题是线程数最大数是 Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至 OOM。
ThreaPoolExecutor
- 创建线程池方式只有一种,就是走它的构造函数,参数自己指定
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
案例
package createThread.threadPoolExecutor;
// 1、创建一个实现Runnable的线程类
public class MyRunnbale implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"正在使用threadPoolExecutor执行");
}
}
package createThread.threadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
//2、定义线程池执行器的相关属性
private static final int CORE_POOL_SIZE=2; //核心线程数
private static final int MAX_POOL_SIZE=5; //最大线程数
private static final int QUEUE_CAPACITY=100; //队列容量
private static final Long KEEP_ALIVE_TIME=1L; //回收时间
public static void main(String[] args) {
//3、创建线程池执行器
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE, //核心线程数
MAX_POOL_SIZE, //最大线程数
KEEP_ALIVE_TIME, //保持存活时间
TimeUnit.SECONDS, //keep_alive时间单位
new ArrayBlockingQueue<>(QUEUE_CAPACITY), //数组阻塞队列
new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略
//4、初始化一个Runnbale线程
MyRunnbale myRunnbale = new MyRunnbale();
for (int i = 0; i < 5; i++) {
//5、执行
executor.execute(myRunnbale);
}
//6、 关闭
executor.shutdown();
}
}
返回结果:
pool-1-thread-2正在使用threadPoolExecutor执行
pool-1-thread-2正在使用threadPoolExecutor执行
pool-1-thread-2正在使用threadPoolExecutor执行
pool-1-thread-2正在使用threadPoolExecutor执行
pool-1-thread-1正在使用threadPoolExecutor执行