java 创建线程的四种方式
作者:(•̀ω•́)y 时间:2023-11-02 21:38:07
1、继承Thread类方式
这种方式适用于执行特定任务,并且需要获取处理后的数据的场景。
举例:一个用于累加数组内数据的和的线程。
public class AdditionThread extends Thread {
private int sum = 0;
private int[] nums;
public AdditionThread(int[] nums, String threadName) {
super(threadName);
this.nums = nums;
}
@Override
public void run() {
for (int num : nums) {
sum += num;
}
}
public int getSum() {
return sum;
}
}
调用方式:
public class Main {
public static void main(String[] args) throws InterruptedException {
int[] nums = {10, 12, 15, 200, 100};
AdditionThread thread = new AdditionThread(nums, "AdditionThread");
thread.start();
thread.join();
System.out.println("sum=" + thread.getSum());
}
}
2、Runnable 接口方式
定义一个实现Runnable接口的类,或者直接创建一个匿名内部类,并覆盖 run() 方法。最后作为参数传给Thread的构造函数。
public class Main {
public static void main(String[] args) {
// 自定义的 Runnable
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable, "Runnable-Thread");
thread.start();
// 自定义匿名内部类
new Thread(() -> {
System.out.println("Inner class");
}).start();
}
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable");
}
}
}
3、 Callable 接口方式
Callable 接口与 Runnable 接口的区别:
(1)Callable 的方法为call(),Runnable的方法为run()。
(2)Callable 的方法由返回值,Runnable 没有。
(3)Callable 的方法声明的Exception,Runnable的没有。
public class Main {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable();
FutureTask<String> task = new FutureTask<>(myCallable);
Thread thread = new Thread(task, "FutureTask");
thread.start();
try {
// 通过get方法获取返回值
String result = task.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
static class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 模拟超时操作
Thread.sleep(1000);
return "OK";
}
}
}
4、线程池方式
我们可以通过 ThreadPoolExecutor 类的构造函数来创建线程池,也可以通过Executors工厂方法来创建,如
// 创建固定线程数的线程池
Executors.newFixedThreadPool();
// 创建只有一个核心线程的线程池
Executors.newSingleThreadExecutor();
// 创建一个没有核心线程,但可以缓存线程的线程池
Executors.newCachedThreadPool();
// 创建一个适用于执行定时任务的线程池
Executors.newScheduledThreadPool();
在创建线程池时,最好传入 ThreadFactory 参数,指定线程池所创建线程的名称。这样有利于分析定位可能存在的问题。
public class Main {
private static final ExecutorService SERVICE =
Executors.newFixedThreadPool(5, new BasicThreadFactory("My-Thread"));
public static void main(String[] args) {
// 打印线程的名字
System.out.println("main thread name:" + Thread.currentThread().getName());
SERVICE.execute(() -> {
System.out.println("Hello thread pool.");
// 打印线程池里的线程的名字
System.out.println("thread name:" + Thread.currentThread().getName());
});
}
static class BasicThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(0);
private final String basicName;
public BasicThreadFactory(String basicName) {
this.basicName = basicName;
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
String name = this.basicName + "-" + threadNumber.incrementAndGet();
thread.setName(name);
return thread;
}
}
}
来源:https://www.cnblogs.com/laishenghao/p/13965258.html?utm_source=tuicool&utm_medium=referral
标签:java,创建,线程
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java线程状态运行原理解析
2023-02-27 05:13:24
![](https://img.aspxhome.com/file/2023/0/78360_0s.jpg)
Intellij IDEA配置Jetty的方法示例
2023-05-02 04:13:12
![](https://img.aspxhome.com/file/2023/7/68707_0s.png)
Java几种常用的断言风格你怎么选
2021-10-30 23:30:32
Java与Kotlin互调原理讲解
2023-08-19 00:07:41
![](https://img.aspxhome.com/file/2023/1/67681_0s.png)
基于Java汇总Spock框架Mock静态资源经验
2023-11-25 04:42:29
C# FileStream实现多线程断点续传
2022-06-19 06:50:56
Android 自定义组件成JAR包的实现方法
2023-04-08 17:56:39
![](https://img.aspxhome.com/file/2023/0/102610_0s.png)
浅谈Java消息队列总结篇(ActiveMQ、RabbitMQ、ZeroMQ、Kafka)
2022-06-13 01:30:40
![](https://img.aspxhome.com/file/2023/8/60698_0s.jpg)
Java集合框架ArrayList源码分析(一)
2022-05-12 19:32:50
java Springboot实现多文件上传功能
2023-11-09 04:31:32
Java反射机制详解_动力节点Java学院整理
2022-08-19 18:10:13
Android实现记住账号密码功能
2021-10-02 01:51:24
![](https://img.aspxhome.com/file/2023/9/137929_0s.jpg)
IDEA远程管理docker镜像及容器服务的实现
2022-01-07 16:26:48
![](https://img.aspxhome.com/file/2023/9/63439_0s.png)
简单了解4种分布式session解决方案
2023-08-09 11:45:49
![](https://img.aspxhome.com/file/2023/7/57717_0s.png)
C#设计模式之Mediator中介者模式解决程序员的七夕缘分问题示例
2021-10-05 16:28:14
![](https://img.aspxhome.com/file/2023/2/89842_0s.png)
C#客户端程序调用外部程序的3种实现方法
2023-06-02 11:39:10
Java如何获取对象属性及对应值
2022-03-30 07:03:05
详解Java ScheduledThreadPoolExecutor的踩坑与解决方法
2022-11-25 17:34:17
![](https://img.aspxhome.com/file/2023/8/69668_0s.png)
El表达式使用问题javax.el.ELException:Failed to parse the expression的解决方式
2023-11-24 12:47:13
![](https://img.aspxhome.com/file/2023/8/59528_0s.png)
Springmvc返回html页面问题如何解决
2021-07-05 09:29:45