java 镶嵌创建线程_Java多线程——之一创建线程的四种方法
1.实现Runnable接口,重载run(),无返回值
package thread;
public class ThreadRunnable implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
package thread;
public class ThreadMain {
public static void main(String[] args) throws Exception {
ThreadRunnable threadRunnable1 = new ThreadRunnable();
ThreadRunnable threadRunnable2 = new ThreadRunnable();
ThreadRunnable threadRunnable3 = new ThreadRunnable();
ThreadRunnable threadRunnable4 = new ThreadRunnable();
Thread thread1 = new Thread(threadRunnable1);
Thread thread2 = new Thread(threadRunnable2);
Thread thread3 = new Thread(threadRunnable3);
Thread thread4 = new Thread(threadRunnable4);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
2.继承Thread类,复写run()
使用时通过调用Thread的start()(该方法是native),再调用创建线程的run(),不同线程的run方法里面的代码交替执行。
不足:由于java为单继承,若使用线程类已经有个父类,则不能使用该方式创建线程。
public class ThreadEx extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread() + ":" + i);
}
}
}
public class ThreadMain {
public static void main(String[] args)
{
ThreadEx threadEx = new ThreadEx();
threadEx.start();
}
}
3.实现Callable接口,通过FutureTask/Future来创建有返回值的Thread线程,通过Executor执行
补充:与实现Runnable接口类似,都是实现接口,不同的是该方式有返回值,可以获得异步执行的结果。
延伸:FutureTask是类,Future是接口。
package thread;
import java.util.concurrent.*;
public class ThreadCallable {
public static void main(String[] args) throws Exception {
FutureTask futureTask = new FutureTask(new Callable() {
public Integer call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
return 1;
}
});
Executor executor = Executors.newFixedThreadPool(1);
((ExecutorService) executor).submit(futureTask);
//获得线程执行状态
System.out.println(Thread.currentThread().getName() + ":" + futureTask.get());
}
}
4.使用Executors创建ExecutorService,入参Callable或Future
补充:适用于线程池和并发
package thread;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import static java.lang.Thread.sleep;
public class ThreadExecutors {
private final String threadName;
public ThreadExecutors(String threadName) {
this.threadName = threadName;
}
private ThreadFactory createThread() {
ThreadFactory tf = new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread();
thread.setName(threadName);
thread.setDaemon(true);
try {
sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
return thread;
}
};
return tf;
}
public Object runCallable(Callable callable) {
return Executors.newSingleThreadExecutor(createThread()).submit(callable);
}
public Object runFunture(Runnable runnable) {
return Executors.newSingleThreadExecutor(createThread()).submit(runnable);
}
}
package thread;
import java.util.concurrent.*;
public class ThreadMain {
public static void main(String[] args) throws Exception {
ThreadExecutors threadExecutors = new ThreadExecutors("callableThread");
threadExecutors.runCallable(new Callable() {
public String call() throws Exception {
return "success";
}
});
threadExecutors.runFunture(new Runnable() {
public void run() {
System.out.println("execute runnable thread.");
}
});
}
}
5 Runnable接口和Callable接口区别
1)两个接口需要实现的方法名不一样,Runnable需要实现的方法为run(),Callable需要实现的方法为call()。
2)实现的方法返回值不一样,Runnable任务执行后无返回值,Callable任务执行后可以得到异步计算的结果。
3)抛出异常不一样,Runnable不可以抛出异常,Callable可以抛出异常。
6 Callable返回值意义在哪儿,不要返回值可以吗,什么时候需要用到返回值?
首先Callable是线程异步执行的结果状态,如果有两个线程A和B,B中的某个业务逻辑中需要确定A结束后才能进行,那么就需要获得线程A的执行结果。
设计背景:一个任务需要进行一系列操作,比如拷贝大量的基础数据,以及解析数据,并入库,由于数量大,整个过程需要持续十秒左右,用户体验差,需要降低到2~5s。
设计思路:经过分解过程,将拷贝数据分为一个过程,同时涵盖部分解析数据功能,剩下解析数据划为一个过程,两个过程异步执行,其中最后一个任务状态入库时需要将所有业务操作都执行完成后更新,此时就需要用到线程中的返回值。
java 镶嵌创建线程_Java多线程——之一创建线程的四种方法相关推荐
- java 当月最后一天_java中取得当月最后一天的四种方法
java中取得当月最后一天的四种方法 第一种,使用Calendar的roll方法,在限制某个日期字段不改变的形式下,改变其他日期字段的值. 第二种,使用Calendar的getActualMaximu ...
- java 线程强制停止线程_java多线程之停止线程
在多线程开发中停止线程是非常重要的技术点. 停止线程在Java语言中并不像break语句那样干脆.须要一些技巧性的处理. 一. 异常法 採用异常法来停止一个线程.首先我们须要了解一下两个方法的使用方 ...
- web java获取当前时间_Java 获取当前系统时间的三种方法
准备工作: import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; 方式一: /** ...
- java发送get请求_java发送http get请求的两种方法(总结)
长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) thro ...
- python两个线程交替打印_三线程按顺序交替打印ABC的四种方法
建立三个线程A.B.C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印. 二.Synchroni ...
- Java中让浮点型数据保留两位小数的四种方法
hello,你好呀,我是灰小猿,一个超会写bug的程序猿! 今天在进行开发的过程中遇到了一个小问题,是关于如何将double类型的数据保留两位小数.突然发现这方面有一点欠缺,就来总结一下. 一.Str ...
- java 内部类 线程_java多线程基本概述(十四)——Thread内部类的几种写法
importjava.util.concurrent.TimeUnit;//命名匿名类-Thread classInnerThread1 {private int countDown = 5;priv ...
- 创建接口匿名实现类的对象的四种方法
package InterfactTest; public class InterfaceTest { public static void main(String[] args) { ...
- java 获取键盘输入法_Java中接收键盘输入的三种方法
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
最新文章
- 愉快的舞会c++_如何在5分钟内建立一个令人愉快的加载屏幕
- 看完GitHub官方的2021年度报告,才发现原来全球程序员好像都在卷呐
- python可变交换性能优化
- python代码示例下载-python下xml解析库lxml最新版下载安装以及代码示例
- 全球及中国手机便携式移动电源行业营销模式及投资竞争力分析报告2021-2027年版
- 安装SAP Business One对软硬件有哪些要求
- [Cocos2d-x For WP8]Scene场景
- Java -- IO
- 输入法相关的使用(跳转)
- Unity视频播放之Video Player的简单使用
- php 输出git fetch,git fetch
- c语言写uart协议实时读写,串口Xmodem协议的发送数据 程序
- vscode自动生成项目目录结构
- vue的事件修饰符之.prevent
- 俄亥俄州立大学计算机科学系,俄亥俄州立大学计算机科学与工程系教授张殷乾老师来实验室作学术报告...
- 程序员数学(15)--分式
- 《计算机网络原理》IP部分
- 【转】perl中$#ARGV是什么意思
- couchbase_Couchbase评论:智能NoSQL数据库
- 从 Azure Databricks 访问 Azure Blob 存储
热门文章
- Angular应用只执行指定单元测试的小技巧
- 如何在 SAP Spartacus 自定义 UI 里使用标准 UI 的上下文数据 - let 关键字的用法
- Angular路由跳转时,如何传递信息
- 从HTTP 400 bad request说起 - 一个函数被注释掉后引起的血案
- SAP Commerce的extensioninfo.xml
- CRM_ORDER_PR_ASSIGN_SELECT_CB
- SAP UI5 busy dialog released more often than required
- oModel.create will also send to backend directly
- directly test Gateway frontend service in AG3 SICF
- Marketing Cloud extension field technical name