Java创立多线程的几种形式

[TOC]

1、继承Thread类,重写run()办法

//形式1package cn.itcats.thread.Test1;public class Demo1 extends Thread{        //重写的是父类Thread的run()    public void run() {        System.out.println(getName()+"is running...");    }            public static void main(String[] args) {        Demo1 demo1 = new Demo1();        Demo1 demo2 = new Demo1();        demo1.start();        demo2.start();    }}

2、实现Runnable接口,重写run()

实现Runnable接口只是实现了线程工作的编写
若要启动线程,须要new Thread(Runnable target),再有thread对象调用start()办法启动线程
此处咱们只是重写了Runnable接口的Run()办法,并未重写Thread类的run(),让咱们看看Thread类run()的实现
实质上也是调用了咱们传进去的Runnale target对象的run()办法

//Thread类源码中的run()办法//target为Thread 成员变量中的 private Runnable target; @Override    public void run() {        if (target != null) {            target.run();        }    }

所以第二种创立线程的实现代码如下:

package cn.itcats.thread.Test1;/** * 第二种创立启动线程的形式 * 实现Runnale接口 * @author fatah */public class Demo2 implements Runnable{    //重写的是Runnable接口的run()    public void run() {            System.out.println("implements Runnable is running");    }        public static void main(String[] args) {        Thread thread1 = new Thread(new Demo2());        Thread thread2 = new Thread(new Demo2());        thread1.start();        thread2.start();    }}

实现Runnable接口相比第一种继承Thread类的形式,应用了面向接口,将工作与线程进行拆散,有利于解耦

3、匿名外部类的形式

实用于创立启动线程次数较少的环境,书写更加简便
具体代码实现:

package cn.itcats.thread.Test1;/** * 创立启动线程的第三种形式————匿名外部类 * @author fatah */public class Demo3 {    public static void main(String[] args) {        //形式1:相当于继承了Thread类,作为子类重写run()实现        new Thread() {            public void run() {                System.out.println("匿名外部类创立线程形式1...");            };        }.start();                                //形式2:实现Runnable,Runnable作为匿名外部类        new Thread(new Runnable() {            public void run() {                System.out.println("匿名外部类创立线程形式2...");            }        } ).start();    }}

4、带返回值的线程(实现implements Callable<返回值类型>)

以上两种形式,都没有返回值且都无奈抛出异样。
Callable和Runnbale一样代表着工作,只是Callable接口中不是run(),而是call()办法,但两者类似,即都示意执行工作,call()办法的返回值类型即为Callable接口的泛型
具体代码实现:

package cn.itcats.thread.Test1;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;import java.util.concurrent.RunnableFuture;/** * 形式4:实现Callable<T> 接口 * 含返回值且可抛出异样的线程创立启动形式 * @author fatah */public class Demo5 implements Callable<String>{    public String call() throws Exception {        System.out.println("正在执行新建线程工作");        Thread.sleep(2000);        return "新建线程睡了2s后返回执行后果";    }    public static void main(String[] args) throws InterruptedException, ExecutionException {        Demo5 d = new Demo5();        /*    call()只是线程工作,对线程工作进行封装            class FutureTask<V> implements RunnableFuture<V>            interface RunnableFuture<V> extends Runnable, Future<V>        */        FutureTask<String> task = new FutureTask<>(d);        Thread t = new Thread(task);        t.start();        System.out.println("提前完成工作...");        //获取工作执行后返回的后果        String result = task.get();        System.out.println("线程执行后果为"+result);    }    }

5、定时器(java.util.Timer)

对于Timmer的几个构造方法

执行定时器工作应用的是schedule办法:

具体代码实现:

package cn.itcats.thread.Test1;import java.util.Timer;import java.util.TimerTask;/** * 办法5:创立启动线程之Timer定时工作 * @author fatah */public class Demo6 {    public static void main(String[] args) {        Timer timer = new Timer();        timer.schedule(new TimerTask() {            @Override            public void run() {                System.out.println("定时工作提早0(即立即执行),每隔1000ms执行一次");            }        }, 0, 1000);    }    }

咱们发现Timer有不可控的毛病,当工作未执行结束或咱们每次想执行不同工作时候,实现起来比拟麻烦。这里举荐一个比拟优良的开源作业调度框架“quartz”,在前期我可能会写一篇对于quartz的博文。

6、线程池的实现(java.util.concurrent.Executor接口)

升高了创立线程和销毁线程工夫开销和资源节约
具体代码实现:

package cn.itcats.thread.Test1;import java.util.concurrent.Executor;import java.util.concurrent.Executors;public class Demo7 {    public static void main(String[] args) {        //创立带有5个线程的线程池        //返回的实际上是ExecutorService,而ExecutorService是Executor的子接口        Executor threadPool = Executors.newFixedThreadPool(5);        for(int i = 0 ;i < 10 ; i++) {            threadPool.execute(new Runnable() {                public void run() {                    System.out.println(Thread.currentThread().getName()+" is running");                }            });        }            }}

运行后果:
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running
pool-1-thread-3 is running
pool-1-thread-5 is running
pool-1-thread-2 is running
pool-1-thread-5 is running
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running

运行结束,但程序并未进行,起因是线程池并未销毁,若想销毁调用threadPool.shutdown(); 留神须要把我下面的
Executor threadPool = Executors.newFixedThreadPool(10); 改为
ExecutorService threadPool = Executors.newFixedThreadPool(10); 否则无shutdown()办法

若创立的是CachedThreadPool则不须要指定线程数量,线程数量多少取决于线程工作,不够用则创立线程,够用则回收。

7、Lambda表达式的实现(parallelStream)

package cn.itcats.thread.Test1;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** * 应用Lambda表达式并行计算 * parallelStream * @author fatah */public class Demo8 {    public static void main(String[] args) {        List<Integer> list = Arrays.asList(1,2,3,4,5,6);        Demo8 demo = new Demo8();        int result = demo.add(list);        System.out.println("计算后的后果为"+result);    }        public int add(List<Integer> list) {        //若Lambda是串行执行,则应程序打印        list.parallelStream().forEach(System.out :: println);        //Lambda有stream和parallelSteam(并行)        return list.parallelStream().mapToInt(i -> i).sum();    }}

运行后果:
4
1
3
5
6
2
计算后的后果为21
事实证明是并行执行

8、Spring实现多线程

(1)新建Maven工程导入spring相干依赖

(2)新建一个java配置类(留神须要开启@EnableAsync注解——反对异步工作)

package cn.itcats.thread;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableAsync;@Configuration@ComponentScan("cn.itcats.thread")@EnableAsyncpublic class Config {    }

(3)书写异步执行的办法类(留神办法上须要有@Async——异步办法调用)

package cn.itcats.thread;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;@Servicepublic class AsyncService {        @Async    public void Async_A() {        System.out.println("Async_A is running");    }        @Async    public void Async_B() {        System.out.println("Async_B is running");    }}

(4)创立运行类

package cn.itcats.thread;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Run {    public static void main(String[] args) {        //构造方法传递Java配置类Config.class        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);        AsyncService bean = ac.getBean(AsyncService.class);        bean.Async_A();        bean.Async_B();    }}
关注公众号:java宝典