目录
方式1⃣️:继承Thread类
// 线程子类
public class SubThread extends Thread {
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("子线程" + i + " ");
}
}
}
// 主线程main
public class MultiThread {
public static void main(String[] args) {
//创建并启动子线程
SubThread thd = new SubThread();
thd.start();
//主线程继续同时向下执行
for (int i = 0; i < 10000; i++) {
System.out.println("主线程" + i + " ");
}
}
}
方式2⃣️:继承Runnable接口
// 线程执行类
public class SubThread implements Runnable {
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("子线程" + i + " ");
}
}
}
// 主线程 main
public class MultiThread {
public static void main(String[] args) {
//创建并启动子线程
Thread t = new Thread(new SubThread());
t.start();
//主线程继续同时向下执行
for (int i = 0; i < 10000; i++) {
System.out.println("主线程" + i + " ");
}
}
}
方式3⃣️:继承Callable接口
子线程实现类
// 实现子线程
public class SubThread implements Callable<Integer>{
private int begin,end;
public SubThread(int begin,int end){
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=begin;i<=end;i++){
result+=i;
}
return result;
}
}
子线程创建启动
// 子线程封装为FutureTask对象,计算1-100的累加和
SubThread subThread1 = new SubThread(1,100);
FutureTask<Integer> task1 = new FutureTask<>(subThread1);
// 子线程封装为FutureTask对象,计算101-200的累加和
SubThread subThread2 = new SubThread(101,200);
FutureTask<Integer> task2 = new FutureTask<>(subThread2);
// 分别启动两个子线程
new Thread(task1).start();
new Thread(task2).start();
// 分别获取两个子线程的计算结果
int sum1 = task1.get();
int sum2 = task2.get();
// 汇总计算结果
int total = sum1 + sum2;
方式4⃣️:创建线程池(实现的callable)
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
//主线程main
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建线程池:最大核心线程,最大线程,存活时间,时间单位,阻塞工作队列(用来储存等待执行的任务)
ExecutorService es = new ThreadPoolExecutor(10, 15, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
// submit()使用Callable接口;返回数据封装在FutureTask类中
// execute()使用Runnable接口
FutureTask<Integer> f = (FutureTask<Integer>) es.submit((Callable<Integer>) new SubThread(1, 10));
int i = f.get();
// 关闭线程(等待线程执行完毕)
es.shutdown();
System.out.println(i);
}
}
//实现子线程
class SubThread implements Callable<Integer> {
private int begin, end;
public SubThread(int begin, int end) {
this.begin = begin;
this.end = end;
}
public Integer call() throws Exception {
int result = 0;
for (int i = begin; i <= end; i++) {
result += i;
}
return result;
}
}