多线程
直接开干不废话,在java中,我们都知道创建线程一般都有两种方法,一种是通过Thread类,一种是实习Runnable接口,这两种都是我们常用的,其实还有几种也可以创建线程。下面重点介绍另外两种。
-
通过Thread类创建线程
static class Thread1 extends Thread{ @Override public void run() { System.out.println("创建线程方式一"); } } //测试 简单的直接用lambda表达式也可以 public static void main(String[] args) { //简单的直接用lambda表达式也可以 new Thread(()-> System.out.println("线程一")).start(); Thread1 thread1 = new Thread1(); thread1.start(); }
-
通过实现Runnable接口创建线程
static class Thread2 implements Runnable { @Override public void run() { System.out.println("创新线程二"); } } public static void main(String[] args) { Thread2 thread2 = new Thread2(); new Thread(thread2).start(); }
-
Callable来创建线程
实现过程是 Callable+ FutureTask+ Thread或许线程池来实现线程的异步任务。
FutureTask是一个课取消的异步计算类
首先来认识试玩一把看看该Callable是如何创建线程的。
/** * 通过Calllable来创建线程,这个接口你补了前面两种执行完任务没有返回值的缺点, * 这个方法执行完任务需要返回值 */ static class Thread3 implements Callable<Integer> { @Override public Integer call() throws Exception { int sum=0; TimeUnit.MILLISECONDS.sleep(1000); for (int i=0 ; i< 100 ; i++){ sum+=i; } return sum; } } public static void main(String[] args) throws ExecutionException, InterruptedException { //1.创建一个实现了Calllable的类 Thread3 thread3 = new Thread3(); //2.创建FutureTask 把步骤一的类(任务)丢个FutureTask去执行 FutureTask task = new FutureTask(thread3); //3.把FutureTask的任务开辟一条线程去执行。 new Thread(task,"线程三").start(); if (!task.isDone()){ System.out.println("任务没完成"+task.isDone()); } if (!task.isCancelled()){ System.out.println("任务是否取消"+task.isCancelled()); } // if (task.cancel(true)) { // System.out.println("取消任务"); // } // if (task.isCancelled()){ // System.out.println("再去确认任务是否取消"+task.isCancelled()); // } //线程一new Thread(()-> System.out.println(Thread.currentThread().getName()+"线程A"),"线程A").start(); //线程二 new Thread(()-> System.out.println(Thread.currentThread().getName()+"线程B"),"线程B").start(); System.out.println(task.get()); System.out.println(Thread.currentThread().getName()+"任务执行完毕"); } } 控制台输出: 任务没完成false 任务是否取消false 线程A线程A 线程B线程B 4950 main任务执行完毕
因为FutureTask是异步计算,而且可以对任务进行取消、判断是否以及完成等操作,当任务没完成是调用get方法获取结果会进行阻塞。
-
通过线程池创建线程
public class Test2 { //静态内部类创建单例线程池 -利用了类机制 static class SinglePool{ public static ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 50, 2000, TimeUnit.SECONDS, new ArrayBlockingQueue(100)); } /** * 通过Calllable来创建线程,这个接口你补了前面两种执行完任务没有返回值的缺点, * 这个方法执行完任务需要返回值 */ static class Thread3 implements Callable<Integer> { @Override public Integer call() throws Exception { int sum=0; TimeUnit.MILLISECONDS.sleep(1000); for (int i=0 ; i< 100 ; i++){ sum+=i; } return sum; } } public static void main(String[] args) throws ExecutionException, InterruptedException { Thread3 thread3 = new Thread3(); ThreadPoolExecutor executor = SinglePool.executor; Future<Integer> task = executor.submit(thread3); executor.shutdown(); System.out.println(task.get()); System.out.println(Thread.currentThread().getName()+"任务执行完毕"); } }