比如目前有一个简单需求是:计算两个变量的和,要求是使用多线程的方式;以下介绍三种创建线程的方式分别做实现。
1、继承Thread类
package com.test.commontest.example.thread;
public class ExtendsThread {
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始!");
Extends1Thread extendsThread = new Extends1Thread(100,100);
extendsThread.start();
extendsThread.join();
System.out.println("异步线程继承Thread类结果:"+extendsThread.getResult());
System.out.println("主线程结束!");
}
static class Extends1Thread extends Thread{
private int param;
private int param1;
private int result;
public Extends1Thread(int param,int param1) {
this.param = param;
this.param1 = param1;
}
public int getResult() {
return result;
}
@Override
public void run() {
result = param + param1;
System.out.println("线程id:"+Thread.currentThread().getId()+"我是继承Thread类的方式!");
}
}
}
2、实现Runnable接口
package com.test.commontest.example.thread;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
public class ImplementsRunnable {
static final CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("主线程开始!");
Implements1Runnable implements1Runnable = new Implements1Runnable(100,100);
Thread thread = new Thread(implements1Runnable);
thread.start();
countDownLatch.await();
System.out.println("异步线程实现Runnable接口结果:"+implements1Runnable.getResult());
System.out.println("主线程结束!");
}
static class Implements1Runnable implements Runnable{
private int param;
private int param1;
private int result;
public Implements1Runnable(int param,int param1) {
this.param = param;
this.param1 = param1;
}
public int getResult() {
return result;
}
@Override
public void run() {
result = param + param1;
System.out.println("线程id:"+Thread.currentThread().getId()+"我是实现Runnable接口的方式!");
countDownLatch.countDown();
}
}
}
3、FutureTask+实现Callable接口
package com.test.commontest.example.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ImplementsCallable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("主线程开始!");
FutureTask futureTask = new FutureTask<>(new Implements1Callable(100, 100));
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("异步线程实现Callable接口结果:"+futureTask.get());
System.out.println("主线程结束!");
}
static class Implements1Callable implements Callable {
private int param;
private int param1;
public Implements1Callable(int param, int param1) {
this.param = param;
this.param1 = param1;
}
@Override
public Integer call() throws Exception {
System.out.println("线程id:"+Thread.currentThread().getId()+"我是实现Callable接口的方式!");
return param + param1;
}
}
}
但是项目中不可能使用以上三种方式进行多线程操作的;因为这种直接创建线程出来使用,使用完毕再销毁的方式不仅会浪费掉创建和销毁线程的时间;而且线程数量不可控,可能导致创建过多线程耗尽服务器资源。一般项目中都是使用线程池,比如spring boot整合线程池
|