共计 5530 个字符,预计需要花费 14 分钟才能阅读完成。
Java 创立多线程的几种形式
[TOC]
1、继承 Thread 类,重写 run() 办法
// 形式 1 | |
package 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") | |
@EnableAsync | |
public class Config {} |
(3) 书写异步执行的办法类 (留神办法上须要有 @Async——异步办法调用)
package cn.itcats.thread; | |
import org.springframework.scheduling.annotation.Async; | |
import org.springframework.stereotype.Service; | |
@Service | |
public 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 宝典