1、继承Thread类
/**
* @program:
* @description: 通过集成Thread类
* @author: wen.yang
* @create: 2020-05-13 19:53
**/
public class MyThead extends Thread {
// 在MyThead类中覆盖Thread类中的run方法.
public void run() {
// 在run方法中编写需要执行的操作
for(int i = 0; i < 5; i ++){
System.out.println("Hello World"+i);
}
}
}
2、实现Runnable接口
/**
* @program:
* @description: 通过实现Runnable接口
* @author: wen.yang
* @create: 2020-05-13 19:53
**/
public class MyThead implements Runnable {
// 在MyThead类中覆盖Thread类中的run方法.
public void run() {
// 在run方法中编写需要执行的操作
for(int i = 0; i < 5; i ++){
System.out.println("Hello World"+i);
}
}
}
3、通过线程池ThreadPoolExecutor启动(而不是java8的Lambda表达式)
/**
* 线程池工具类
*
* @param threadPoolName 线程池名称
* @param corePoolSize 核心线程数
* @param maximumPoolSize 最大线程数
* @param queueSize 队列容量
* @return
*/
public static ExecutorService getExecutorService(String threadPoolName, int corePoolSize, int maximumPoolSize, int queueSize) {
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(threadPoolName + "-%d").build();
ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(queueSize), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
return pool;
}
4、通过Callable和Future创建线程
(1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
(2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
(3)使用FutureTask对象作为Thread对象的target创建并启动新线程。
(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author yangwen
*/
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args) {
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
if (i == 20) {
new Thread(ft, "有返回值的线程").start();
}
}
try {
System.out.println("子线程的返回值:" + ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception {
int i = 0;
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
}