Java中创建线程的几种方式

Java创建线程的几种方式

①继承thread类,重写其中的run方法,调用run方法执行方法体中的线程任务

调用线程对象的start的方法创建并启动线程

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args){
class MyThread extends Thread{
@override
public void run(){
sys("创建了自己的线程");
}
}
MyThread mythread = new MyThread();
mythread.start();
}

②实现runnable接口,重写其中的run方法,run方法中的方法体就是线程的方法体

以Runnable中的实例作为thread的taget创建线程对象

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
class MyRunnable implements Runnable {
@Override
public void run(){
sys("线程创建成功");
}
}
MyRunnable myrunnable = new MyRunnable();
Thread thread = new Thread(myrunnable);
thread.start();
}

③实现callable接口,重写接口中的call方法,call方法将作为线程的执行体,带返回值

Callable通常搭配Future Task使用,它的作用就是用来保存callable的返回值,等待结果出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args){
// 创建线程计算1+2+...1000
Callable<Integer> callable = new Callable<Integer>();
@override
public Integer call(){
int sum = 0;
for(int i = 0;i<=1000;i++){
sum+=i;
}
return sum;
}
// 创建一个task来接收返回值
FutureTask task = new FutureTask(callable);

// 创建一个线程工作
Thread t = new Thread(task);
t.start();

// 线程中callable完成任务并返回结果给
sys.out.println(task.get());
}

④通过线程池创建

创建线程池

使用Excutors.newFixThreadPool()可以创建固定线程数的线程池

返回值类型:ExecutorService

注册一个任务到线程池中:ExecutorsService.submit

1
2
3
4
5
6
7

public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.submit(()->{
System.out.println("一个在 线程池 中的线程 创建完成!");
});
}

小tips:

Executors创建线程池的一些方法

  1. newcashedThreadPool 创建线程数动态增长的线程池

  2. newFixedThreadPool 创建固定线程数的线程池

  3. newSingleThreadExecutor 创建只包含一个线程的线程池

  4. newScheduledThreadPool 设定延迟时间后执行命令,或者定期执行


Java中创建线程的几种方式
http://owoah.com/2023/04/07/Java创建线程的几种方式/
作者
owoah
发布于
2023年4月7日
许可协议