多线程-实现多线程的几种方案
来源:互联网 发布:python 执行外部程序 编辑:程序博客网 时间:2024/06/07 18:22
三种实现多线程的方式:
无返回值:继承Thread类,或者实现Runnable接口(如果当前类已经继承了其他类)
有返回值:实现Callable接口
public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException{ // thread class ThreadTest1 threadTest1 = new ThreadTest1(); threadTest1.start(); // Runnable interface ThreadRunnableTest threadRunnableTest = new ThreadRunnableTest(); Thread thread = new Thread(threadRunnableTest); thread.start(); // Callable interface System.out.println("----程序开始运行----"); Date date1 = new Date(); int taskSize = 8; // 创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(taskSize); // 创建多个有返回值的任务 List<Future> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { Callable<Object> c = new ThreadCallableTest(i + ""); Future f = pool.submit(c); list.add(f); } // 关闭线程池 pool.shutdown(); // 获取所有并发任务的运行结果 for (Future f : list) { // 从Future对象上获取任务的返回值,并输出到控制台 System.out.println(">>>" + f.get().toString()); } Date date2 = new Date(); System.out.println("----程序结束运行----,程序运行时间【" + (date2.getTime() - date1.getTime()) + "毫秒】"); }
public class ThreadCallableTest implements Callable<Object> { private String taskNum; public ThreadCallableTest(String taskNum) { this.taskNum = taskNum; } @Override public Object call() throws Exception { System.out.println(">>>" + taskNum + "任务启动"); System.out.println(Thread.currentThread().getName()); Date dateTmp1 = new Date(); //Thread.sleep(100); Date dateTmp2 = new Date(); long time = dateTmp2.getTime() - dateTmp1.getTime(); System.out.println(">>>" + taskNum + "任务终止"); return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】"; }}
public class ThreadRunnableTest implements Runnable{ @Override public void run() { System.out.println("测试runnable接口"); }}
public class ThreadTest1 extends Thread{ public void run(){ System.out.println("测试Thread"); }}
线程池,信号量。。。
0 0
- 多线程-实现多线程的几种方案
- iOS多线程实现的几种方案
- 多线程的实现方案
- 多线程几种常用方案
- 多线程的几种实现方法详解
- java多线程的几种实现方法
- Linux kernel多线程的几种实现
- iOS 多线程的几种实现方式
- 多线程的几种实现方法详解
- 多线程的几种实现方法
- 多线程的几种实现方法详解
- 多线程的几种实现方法详解
- Linux kernel多线程的几种实现
- 8.19 多线程的几种实现方式
- Linux kernel多线程的几种实现
- Linux kernel多线程的几种实现
- 多线程的几种实现方式
- 多线程的几种实现方式
- Swing开发之JProgressBar篇
- RxJava
- Timing Wheel 定时轮算法
- 如何将java工程转变为web工程
- css引入外部字体
- 多线程-实现多线程的几种方案
- delphi protobuf
- POM .xml 报 Missing artifact 异常
- valgrind使用日志
- [LeetCode]Factorial Trailing Zeroes
- 工作总结26 Error while trying to retrieve text for error ORA-12154 解决方案
- 高仿苹果7 plus 3592H
- Hibernate框架学习(第二讲)---开发第一个Hibernate配置
- mysql-5.6 linux安装方法详细记录