通过实现Runnable接口来实现
public class T01_CreateThread { // 创建线程的三种方式 public static void main(String[] args) {// 通过实现Runnable接口来创建Thread线程// 1、写一个类实现Runnable 接口// 2、创建一个对象 RunnableMe runnableMe = new RunnableMe();// 3、由runnable 创建一个thread 对象// 4、通过调用start 方法来启动一个线程 new Thread(runnableMe, " i am runnable thread").start();// 注意坑,此只是调用了run方法并不是启动了一个线程,通过查看 线程name ,发现打印的是 主线程的名字 main runnableMe.run(); System.out.println("main: " + Thread.currentThread().getName()); } // 实现 runnable 接口 private static class RunnableMe implements Runnable { @Override public void run() { System.out.println("i am thread runnable " + Thread.currentThread().getName()); } }}输出结果:i am thread runnable maini am thread runnable i am runnable threadmain: main
通过实现Callable接口来实现
public class T01_CreateThread { // 创建线程的三种方式 public static void main(String[] args) { //// 通过实现Callable 接口来实现// 由Callable<Integer>创建一个FutureTask<Integer>对象: FutureTask<Integer> oneTask = new FutureTask<Integer>(new CallableMe());// FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。// 由FutureTask<Integer>创建一个Thread对象: new Thread(oneTask, "i am FutureTask").start(); System.out.println("main: " + Thread.currentThread().getName()); } private static class CallableMe implements Callable { @Override public Object call() throws Exception { System.out.println("i am thread CallableMe " + Thread.currentThread().getName()); return 0; } }}输出结果:main: maini am thread CallableMe i am FutureTask
继承Thread 类实现创建线程
public class T01_CreateThread { // 创建线程的三种方式 public static void main(String[] args) {// 1 通过继承 thread 来实现 ThreadMe threadMe = new ThreadMe(" i am extends thread");// 启动线程 threadMe.start(); // } // 继承 thread private static class ThreadMe extends Thread { public ThreadMe(String name) { super(name); } @Override public void run() { System.out.println("i am thread extends thread " + Thread.currentThread().getName()); } }}输出结果:i am thread extends thread i am extends thread
通过Executors 框架来进行创建( 阿里规约明确规定不允许使用此框架,要求手动创建线程池,目的是明确每个 参数的作用)
ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());参数说明// 1、corePoolSize, 指定了线程池里的线程数量,核心线程池大小// 2、maximumPoolSize, 指定了线程池里的最大线程数量// 3、keepAliveTime, 当线程池线程数量大于corePoolSize时候,多出来的空闲线程,多长时间会被销毁。// 4、unit 时间单位。TimeUnit// 5、workQueue 任务队列,用于存放提交但是尚未被执行的任务。我们可以选择如下几种:// ArrayBlockingQueue:基于数组结构的有界阻塞队列,FIFO。// LinkedBlockingQueue:基于链表结构的有界阻塞队列,FIFO。// SynchronousQueue:不存储元素的阻塞队列,每个插入操作都必须等待一个移出操作,反之亦然。// PriorityBlockingQueue:具有优先级别的阻塞队列。// 6、threadFactory 线程工厂,用于创建线程,一般可以用默认的// 7、handler 拒绝策略,所谓拒绝策略,是指将任务添加到线程池中时,线程池拒绝该任务所采取的相应策略。// 当向线程池中提交任务时,如果此时线程池中的线程已经饱和了,而且阻塞队列也已经满了,则线程池会选择一种拒绝策略来处理该任务,该任务会交给RejectedExecutionHandler 处理。// 线程池提供了四种拒绝策略:// AbortPolicy:直接抛出异常,默认策略;// CallerRunsPolicy:用调用者所在的线程来执行任务;// DiscardOldestPolicy:丢弃阻塞队列中靠最前的任务,并执行当前任务;// DiscardPolicy:直接丢弃任务;